我在 iOS 6 上使用 xcode 4.5(4G182)。NSDateFormatter 在 iOS 6 中显示错误的年份,如何解决?
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
NSString *str = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@ == %@",str,[[dateFormatter dateFromString:str] description]);
打印出“2012-09-14 == 2011-09-13 16:00:00 +0000”
最佳答案
YYYY
与 yyyy
不同。
根据this page其中iOS Date format page引用文献;
`y`: Year
`Y`: Year (in "Week of Year" based calendars). This year designation is used in
ISO year-week calendar as defined by ISO 8601, but can be used in
non-Gregorian based calendar systems where week date processing is desired.
May not always be the same value as calendar year.
执行句是最后一句。请改用yyyy
。
有关使用 YYYY
时年份值如何以及为何可能出现偏差的更多详细信息:
The ISO week-numbering year starts at the first day (Monday) of week 01 and ends at the Sunday before the new ISO year (hence without overlap or gap). It consists of 52 or 53 full weeks. The ISO week-numbering year number deviates from the number of the traditional Gregorian calendar year on a Friday, Saturday, and Sunday, or a Saturday and Sunday, or just a Sunday, at the start of the traditional Gregorian calendar year (which are at the end of the previous ISO week-numbering year) and a Monday, Tuesday and Wednesday, or a Monday and Tuesday, or just a Monday, at the end of the traditional Gregorian calendar year (which are in week 01 of the next ISO week-numbering year). For Thursdays, the ISO week-numbering year number is always equal to the traditional Gregorian calendar year number.
Examples:
Monday 29 December 2008 is written "2009-W01-1"
Sunday 3 January 2010 is written "2009-W53-7"
来自https://en.wikipedia.org/wiki/ISO_8601#Week_dates (添加了粗体样式)
关于NSDateFormatter 显示错误的年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12423179/