【问题标题】:NSDate setting the time, not the expected resultNSDate 设置时间,而不是预期的结果
【发布时间】:2012-11-06 12:00:39
【问题描述】:

我有以下代码通过使用日期中的 YEAR、MONTH 和 DAY 组件来将日期的时间设置为 0 小时、0 分钟和 0 秒:

NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate:date];
NSDate *newDate = [gregorian dateFromComponents:comps];
NSLog(@"date: %@, newDate: %@", date, newDate);

输出是:

date: 2012-11-06 11:44:09 +0000, newDate: 2012-11-05 23:00:00 +0000

但我希望新日期是:2012-11-06 00:00:00 +0000 发生了什么事我应该知道的?

【问题讨论】:

    标签: ios datetime nsdate nscalendar nsdatecomponents


    【解决方案1】:

    NSLog 使用-[NSDate description] 显示日期,而-[NSDate description] 又将存储在NSDate 中的绝对时间转换为字符串。此转换使用 UTC 作为时区完成。

    对于您的情况,最好也使用 UTC 进行日期计算。为此,请调整执行计算的日历对象:

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    

    【讨论】:

      【解决方案2】:

      请参阅 this answer 了解类似的 Stack Overflow 问题。

      这应该可以解决您的夏令时问题:

      NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
      
      [formatter setCalendar:[NSCalendar currentCalendar]];
      [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
      
      NSString *string = [formatter stringFromDate:[NSDate date]];
      

      【讨论】:

      • 使用上述格式化程序设置打印日期是一样的。您能否就夏令时如何影响 NSDate 创建或日历提供一些说明?
      • 夏令时会通过考虑设备/用户设置的时区来影响[NSDate date] 的结果。通过使用不同的时区,可以确定与另一个时区相关的日期。请参阅对我的回答所做的修改。
      • @CaptainRedmuff “夏令时会影响 [NSDate date] 的结果”:这不是真的; NSDate 不受日历、时区、语言环境等影响。NSDate 表示绝对时间点。
      猜你喜欢
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      相关资源
      最近更新 更多