我正在尝试生成具有固定小时和分钟的 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 忽略了我的要求,组件的含义是什么?
我究竟做错了什么 ?