【问题标题】:Number of days between two NSDate dates with time zone带时区的两个 NSDate 日期之间的天数
【发布时间】:2012-09-01 23:10:09
【问题描述】:

我计算两个日期之间的天数:

NSDateComponents *datesDiff = [calendar components: NSDayCalendarUnit 
                                          fromDate: someDate
                                            toDate: currentDate
                                           options: 0];

但是这种方法有一个缺点 - 它没有考虑时区。 因此,例如,如果我在 +2GMT 并且当地时间是凌晨 1:00,则当前日期是昨天。

如何比较指定时区的日期(没有“黑客”)?

PS:通过计算时差来防止答案,我需要实际天数的差异:

  • yesterday 23:00today 1:00 - 1 day
  • yesterday 1:00today 23:00 - 1 day
  • today 1:00today 23:00 - 0 days

  • (所有这些都在当前时区)

【问题讨论】:

  • 为什么不将两者都转换为纪元,然后计算出它已经过了多少天?
  • 我的想法是,如果您确定每个日期自纪元以来的秒数,然后找到两者之间的差异..您可以通过除以秒数来找到天数天(86,400)。但是,可能有更好的方法来做到这一点 - 你读过documentation吗?
  • 我知道比较秒。但是这种方法给出了错误的结果 - 请看我问题末尾的示例。

标签: timezone compare nsdate


【解决方案1】:

我不知道它是否符合你的标准,但一个相当简单的方法似乎是定义一个 GMT 调整日期,如下所示:

NSDate *newDate = [oldDate dateByAddingTimeInterval:(-[[NSTimeZone localTimeZone] secondsFromGMT])

更多详情请见this question

【讨论】:

    【解决方案2】:

    您为什么不将日期格式化程序配置为将所有日期默认为 GMT 时间,然后进行比较。

        NSDate *now = [NSDate date]; 
        NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
        NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT"]; // Sets to GMT time. 
    
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
        [formatter setCalendar:gregorianCalendar]; 
        [formatter setTimeZone:timeZone]; 
        [formatter setDateFormat:@"yyyyMMddHH"];
    
        NSString *dateString = [formatter stringFromDate:now]; 
      // do whatever with the dates
        [gregorianCalendar release]; 
        [formatter release];
    

    【讨论】:

    • 在 GMT 时区,例如 21:00 和 23:00 相差 0 天,但在 GMT+2(用户居住的地方)则相差 1 天。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 2012-05-30
    • 2012-10-25
    相关资源
    最近更新 更多