同一日期的NSDate和NSDateComponent值之间的差异 [英] Difference between NSDate and NSDateComponent value for the same date

查看:88
本文介绍了同一日期的NSDate和NSDateComponent值之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的函数来获取一周中的第一天和最后一天. 通过查看NSLog输出,我发现同一日期的NSDate描述符和组件日期返回了不同的值,为什么?

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 ?

此处的NSLog输出:

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 

如您所见,NSDATE是4月3日,第一行的天分量是4,第二行是9和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.

代码在这里:

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

推荐答案

您的日期以+0000(UTC)的时区打印,而您的NSCalendar实例(以及您的NSDateComponents)正在使用设备的默认时区(即我猜想是 UTC + 2 ).

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

这篇关于同一日期的NSDate和NSDateComponent值之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆