gpt4 book ai didi

objective-c - 同一日期的 NSDate 和 NSDateComponent 值之间的差异

转载 作者:行者123 更新时间:2023-11-29 05:05:27 25 4
gpt4 key购买 nike

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

这里 NSLog 输出:

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。

代码如下:

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

关于objective-c - 同一日期的 NSDate 和 NSDateComponent 值之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5555627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com