我正在尝试生成一个具有固定小时和分钟的 NSDate。我需要它与 CoreData 中存储的其他日期进行同等比较。
到目前为止我写了这段代码:
NSDate date = [NSDate date];
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* newDate = [calendar dateFromComponents:components];
但是通过 xcode4 中的断点我可以看到这些值:
Printing description of date:
2012-01-10 11:20:47 +0000
Printing description of newDate:
2012-01-09 23:00:00 +0000
为什么 newDate 比 date 晚一天?
/* 编辑 */
我也尝试过手动设置所有组件,但日历 dateFromComponents 总是返回相同的一小时回溯日期,似乎忽略了这些组件。
components.hour=0;
components.minute=0;
components.second=0;
components.timeZone=[NSTimeZone localTimeZone];
这是设置后组件的描述:
<NSDateComponents: 0x7464de0>
TimeZone: Europe/Rome (CET) offset 3600
Calendar Year: 2012
Month: 1
Day: 10
Hour: 0
Minute: 0
Second: 0
这正是我想要的,但是使用此组件计算的日期仍然是
Printing description of newDate:
2012-01-09 23:00:00 +0000
我想知道为什么即使指定 NSDateComponents 中的所有组件也无法获得精确的 NSDate。仅仅因为 NSCalendar 忽略了我的要求,组件的含义是什么?
我做错了什么?
最佳答案
我猜你所在时区是+01:00。实际上,NSDate 总是以 GMT 给出值。因此,如果是 1 月 10 日 00:00,那么同时 GMT 时间是 1 月 9 日 23:00。
甚至,在打印以下行时
2012-01-10 11:20:47 +0000,
它应该比当前时间少打印 1 小时。请检查。
关于objective-c - 生成固定时间的 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8802636/