我试图增加一个日期并获得每个月的格式化输出......它工作正常,但从 2010 年 12 月到 2011 年 1 月的步骤不起作用。请看一下:
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *lastDate = [[NSDate alloc] init];
for (int i = 0; i < 12; i++) {
NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease];
[offsetComponents setMonth: 1];
lastDate = [[gregorian dateByAddingComponents:offsetComponents toDate: lastDate options:0] retain];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateFormat:@"MMMM YYYY"];
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease];
[dateFormatter setLocale:locale];
NSLog(@"%d: Fromatted Date: %@ from : %@", i, [dateFormatter stringFromDate:lastDate], lastDate);
}
调试输出:[会话开始于 2010-07-01 11:05:18 +0200。] 0:起始日期:2010 年 8 月从:2010-08-01 11:05:19 +0200
1: 开始日期: 2010 年 9 月 : 2010-09-01 11:05:19 +0200
2: 起始日期: 2010 年 10 月起始日期: 2010-10-01 11:05:19 +0200
3:开始日期:2010 年 11 月开始:2010-11-01 11:05:19 +0100 4:开始日期:2010 年 12 月开始:2010-12-01 11:05:19 +0100
5: Fromatted Date: January 2010 from : 2011-01-01 11:05:19 +0100 <--- 为什么是 2010 年?!
6: 起始日期: 2011 年 2 月起始于 : 2011-02-01 11:05:19 +0100
7: 起始日期: 2011 年 3 月起始于 : 2011-03-01 11:05:19 +0100
8: 开始日期: 2011 年 4 月 : 2011-04-01 11:05:19 +0200
9: 起始日期: 2011 年 5 月起始于 : 2011-05-01 11:05:19 +0200
10: 起始日期: 2011 年 6 月起始时间: 2011-06-01 11:05:19 +0200
11: 开始日期: 2011 年 7 月 : 2011-07-01 11:05:19 +0200