NSDateFormatter 显示错误的年份

标签 nsdateformatter ios6

我在 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”

最佳答案

YYYYyyyy 不同。

根据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/

相关文章:

macos - 芬兰语 : How to specify Unicode Date Formatter (like MMMM yyyy) to work in Finnish language

objective-c - NSDateFormatter 具有自定义格式的相对日期格式

iphone - nsdateformatter 不适用于日本日历

iOS Facebook 3.1 API - "Posted by"未显示我们的应用

ios - Cordova 2.2 - 升级后应用程序运行速度变慢

ios - pushViewController 做一个黑色 View

ios - 这个日期字符串是什么格式?

ios - 如何将字符串日期和时间格式化为2012年12月4日星期二下午5:30

ios - 覆盖 MFMailComposeViewController 的 UIAppearance 属性

view - UICollectionView嵌入youtube视频仍在另一 View 中播放