我正在尝试创建 datefromstring。但是,创建的日期是错误的。任何人都可以看到我的代码有什么问题吗?
这是代码:
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MM/dd/YYYY hh:mm"];
[format setTimeZone:[NSTimeZone localTimeZone]];
NSString *datePart = [txtView.text substringToIndex:16];
NSLog(@"datepart: '%@'", datePart);
NSDate *midDate = [format dateFromString:datePart];
NSLog(@"format middate: %@", [format stringFromDate:midDate]);
这是输出:
datepart: '04/29/2013 04:23'
format middate: 01/05/2013 04:23
无论如何都不是 1 月 - 为什么这么不正确??
谢谢! R
最佳答案
来自Date Formatting Guide documentation :
[This example] uses yyyy to specify the year component. A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.
我已经使用 YYYY 和 yyyy 运行了代码示例,yyyy 产生了正确的结果。
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MM/dd/yyyy hh:mm"];
[format setTimeZone:[NSTimeZone localTimeZone]];
NSString *datePart = @"04/29/2013 04:23";
NSLog(@"datepart: '%@'", datePart);
NSDate *midDate = [format dateFromString:datePart];
NSLog(@"format middate: %@", [format stringFromDate:midDate]);
打印出来
2013-04-29 21:40:42.450 Untitled[95290:707] datepart: '04/29/2013 04:23'
2013-04-29 21:40:42.453 Untitled[95290:707] format middate: 04/29/2013 04:23
有趣的事实!
这是 Apple 在 2013 年初出现的请勿打扰错误的原因,他们使用 YYYY 而不是 yyyy。 Some more info here.
关于ios - 为什么我的 NSDateFormatter 创建了错误的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16287638/