1

我正在创建这样的日期:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY"];
NSInteger year = [[dateFormatter stringFromDate:[NSDate date]] intValue];
NSLog(@"NSInteger YEAR : %d\n", year);

//minutes, hours, day and month are initialized elsewhere...

NSDateComponents *comps = [[NSDateComponents alloc] init];      
[comps setYear:year];
[comps setMonth:month];
[comps setDay:day];
[comps setHour:hours];
[comps setMinute:minutes];
NSDate *sampleDate = [gregorian dateFromComponents:comps];

NSLog(@"sampleDate YEAR : %d\n", [[dateFormatter stringFromDate:sampleDate] intValue]);

我的问题是当日期是 1 月 1 日或 1 月 2 日时,年份不正确。这里应该是 2010 年(当我检索今天的年份时),但实际上是 2009 年......我不明白为什么!而这只发生在这两天......

你知道为什么会这样吗?先感谢您。

4

1 回答 1

6

请参阅Unicode 标准。“yyyy”(小写)为您提供年份,但“YYYY”(大写)为您提供日期所在周的年份(也就是说,如果日期在去年的第 52 周内,则 YYYY 将是去年)。

于 2010-06-17T15:34:13.927 回答