Monday, January 03, 2011

NSDateFormatter setDateFormat YYYY return wrong year

On the first day of 2011, I found that the date formatter return a wrong year.
2011-01-01 is converted ot "2010年01月01日"
while 2011-01-02 ,2011-01-03 is converted correctly.

It's because the format string YYYY represent the "Year (of "Week of Year"), used in ISO year-week calendar. May differ from calendar year."




2011-01-01 is Saturday, and the year of "week of year" is 2010.
To fix the problem, use "yyyy" instead of "YYYY".
Here's code sample:

NSDateFormatter *fmt1 = nil;
fmt1 = [[NSDateFormatter alloc] init];
[fmt1 setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [fmt1 dateFromString:@"2010-01-01"];

fmt = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_HK"];
[fmt setLocale:locale];
[locale release];
//[fmt setDateFormat:@"YYYY年MM月dd日"];
[fmt setDateFormat:@"yyyy年MM月dd日"];
[fmt ​stringFromDate:date];

The iOS follows Unicode standard. For more infomation, please refer to
http://unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns

Hope it can help you save some time.
Happy New Year!

You may also want to check this out
Situee's Blog - iPhone,Technology: NSDateFormatter:Convert NSDate to NSString description

No comments:

Post a Comment