2

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

我究竟做错了什么 ?

4

3 回答 3

3

我猜你是 +01:00 时区。实际上 NSDate 总是在 GMT 中给出值。所以如果是 1 月 10 日 00:00,那么同时 GMT 时间是 1 月 9 日 23:00。

甚至,在打印以下行时

2012-01-10 11:20:47 +0000,

它应该比您当前的时间少打印 1 小时。请检查。

于 2012-01-10T11:44:03.887 回答
1

用这个....

  NSDate *date = [NSDate date];    
  NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  [gregorian setLocale:[NSLocale currentLocale]];
  NSDateComponents *nowComponents = [gregorian components:NSYearCalendarUnit |           NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:date];
   NSDate* newDate = [gregorian dateFromComponents:nowComponents];
   NSLog(@"%@\n%@",date,newDate);
于 2012-01-10T11:50:40.550 回答
0

您可能对时区有疑问,请尝试为日历设置时区。

于 2012-01-10T11:44:45.157 回答