Difference between NSDate and NSDateComponent valu

2020-02-02 03:31发布

问题:

I created a simple function to get first and last day of a week for a day in it. Looking at the NSLog output i found that different values are returned from a NSDate descriptor and component day for the same date, why ?

Here NSLog outputs:

NSDATE: 2011-04-03 22:00:00 +0000, DAY COMPONENT: 4 
NSDATE: 2011-04-09 22:00:00 +0000, DAY COMPONENT: 10 

As you can see, NSDATE is 3 of April and day component is 4 for the first row, and respectively 9 and 10 for the second one.

Here the code:

NSDate *date = [NSDate date]; //Today is  April 5th 2011
NSCalendar *cal =[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];

[cal setFirstWeekday:2]; //My week starts from Monday

//DEFINE BEGINNING OF THE WEEK
NSDate *beginningOfWeek = nil;
[cal rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek interval:nil forDate:date];
NSDateComponents *beginComponents = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit) fromDate:beginningOfWeek];

//DEFINE END OF THE WEEK, WITH 6 days OFFSET FROM BEGINNING
NSDateComponents *offset = [[NSDateComponents alloc]init];
[offset setDay:6];
NSDate *endOfWeek = [cal dateByAddingComponents:offset toDate:beginningOfWeek options:0];
NSDateComponents *endComponents = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit) fromDate:endOfWeek];

NSLog(@"NSDATE: %@, DAY COMPONENT: %d",beginningOfWeek, [beginComponents day]);
NSLog(@"NSDATE: %@, DAY COMPONENT: %d",endOfWeek,       [endComponents day]);

回答1:

Your dates are being printed with a timezone of +0000 (UTC), while your NSCalendar instance (and therefore your NSDateComponents) is using your device's default timezone (which I would guess is UTC+2).