创建1月1日和2日的NSDate时的奇怪行为

leo*_*hab 1 iphone objective-c nsdate nscalendar nsdatecomponents

我正在创建这样的日期:

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]);
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*ith 6

请参阅Unicode标准."yyyy"(小写)给你一年,但"YYYY"(大写)给你一个星期的一年(也就是说,如果日期在去年的第52周,YYYY将是去年).