Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

iphone - NSDateFormatter +dateFormatFromTemplate:options:locale: BUG?

Please see below codes and output.

 NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
 [dateComponents setYear:2011];
 [dateComponents setMonth:1];
 [dateComponents setDay:1];

 NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];

 NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
 [dateFormatter setDateFormat:[NSDateFormatter dateFormatFromTemplate:@"YYYYMMMd" options:0 locale:[NSLocale currentLocale]]];

 NSString *dateString = [dateFormatter stringFromDate:date];

 NSLog(@"Happy New Year: %@", dateString);

What do you expect for output?

 Happy New Year: Jan 1, 2011

But the result is...

 Happy New Year: Jan 1, 2010

What's wrong? Please help...

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The template format string should be @"yyyyMMMd" (lowercase "y" for year).

Uppercase "Y" is something else (see Unicode Date Format Patterns).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...