Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

ios6 - NSDateFormatter show wrong year

im using xcode 4.5(4G182) with iOS 6. NSDateFormatter show wrong year in iOS 6, how to solve?

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
NSString *str = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@ == %@",str,[[dateFormatter dateFromString:str] description]);

it print out "2012-09-14 == 2011-09-13 16:00:00 +0000"

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

YYYY is not the same as yyyy.

According to this page which the iOS Date format page references;

`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.

The operative sentence being the last one. Use yyyyinstead.


Further details on how and why the year values may deviate when using 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"

From https://en.wikipedia.org/wiki/ISO_8601#Week_dates (bold styling added)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...