【问题标题】:Producing an NSDate with fixed time生成具有固定时间的 NSDate
【发布时间】:2012-02-06 19:50:51
【问题描述】:

我正在尝试生成具有固定小时和分钟的 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 比日期早一天?

/* 编辑 */

我也尝试手动设置所有组件,但日历 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 忽略了我的要求,组件的意义何在?

我做错了什么?

【问题讨论】:

    标签: objective-c nsdate nsdatecomponents


    【解决方案1】:

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

    甚至,在打印以下行时

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

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

    【讨论】:

    • 我刚刚验证过,[NSDate date] 实际上是根据 GMT 给出当前日期和时间。所以上面的代码设置固定时间是不正确的。
    【解决方案2】:

    使用这个....

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2014-02-20
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 2014-06-12
        • 2016-10-16
        • 2021-02-02
        • 2013-09-25
        相关资源
        最近更新 更多