53

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

4

1 回答 1

156

YYYY不一样yyyy

根据iOS日期格式页面引用的this 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

ISO 周编号年从第 1 周的第一天(星期一)开始,到新 ISO 年之前的星期日结束(因此没有重叠或间隙)。它由 52 或 53个整周组成。ISO 周编号年份编号在传统公历年开始时(位于上一个 ISO 周编号年的结束)和一个星期一、星期二和星期三,或者星期一和星期二,或者只是一个星期一,在传统的公历年(在 ISO 下一个周的第 01 周)结束时-编号年份)。对于星期四,ISO 周编号年份编号始终等于传统的公历年份编号。

例子:

2008 年 12月29 日星期一写成“ 2009 -W01-1”

2010 年1 月3 日星期日写成“ 2009 -W53-7”

来自https://en.wikipedia.org/wiki/ISO_8601#Week_dates (添加了粗体样式)

于 2012-09-14T11:07:18.630 回答