开发者

Difference between NSDate and NSDateComponent value for the same date

开发者 https://www.devze.com 2023-02-22 19:42 出处:网络
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 t

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",begi开发者_运维问答nningOfWeek, [beginComponents day]);
NSLog(@"NSDATE: %@, DAY COMPONENT: %d",endOfWeek,       [endComponents day]);


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消