Weird behavior when creating an NSDate of January

2020-04-21 02:29发布

I'm creating a date like this :

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]);

My problem is that when the date is January 1st or January 2nd, the year is not correct.. Here it should be 2010 (as I retrieve today's year), but actually it is 2009... I don't understand why ! And this is only happening for those 2 days...

Do you have any idea why is it that way ? Thank you in advance.

1条回答
我只想做你的唯一
2楼-- · 2020-04-21 03:06

See the Unicode standard. "yyyy" (lower case) gives you the year, but "YYYY" (upper case) gives you the year for the date's week (that is, if the date is within the 52nd week of the last year, YYYY will be last year).

查看更多
登录 后发表回答