【问题标题】:NSDateComponents issue - incorrect dayNSDateComponents 问题 - 不正确的日期
【发布时间】:2011-10-20 08:09:43
【问题描述】:

我有一个 NSDateComponents 问题。我有两个 NSDate,我试图通过检查它们的年、月和日是否匹配来进行比较。我通过将 NSDate 值转换为这些整数组件来做到这一点,如下所示:

//NSDate *cgiDate is previously set to 2011-08-04 00:00:00 +0000 
//NSDate *orderDate is previously set to 2011-08-04 14:49:02 +0000
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *cgiDateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) fromDate:cgiDate];
NSCalendar *orderCalendar = [NSCalendar currentCalendar];
NSDateComponents *orderDateComponents = [orderCalendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) fromDate:orderDate];
if (([cgiDateComponents day] == [orderDateComponents day]) &&
    ([cgiDateComponents month] == [orderDateComponents month]) &&
    ([cgiDateComponents year] == [orderDateComponents year])) {
       GHTestLog(@"MATCHED");
 } else {
       GHTestLog(@"Not matched");
       GHTestLog(@"Day: %d vs. %d", [cgiDateComponents day], [orderDateComponents day]);
 }

我的结果不匹配,第 3 天 vs. 4 天。为什么会这样?

我非常感兴趣地阅读了以下问题: NSDateComponents - day method returning wrong dayhttps://stackoverflow.com/questions/3920445/nsdatecomponents-incorrectly-reporting-day 但是两者都没有回答我为什么这不起作用的问题。

有什么建议吗?

【问题讨论】:

    标签: objective-c cocoa-touch ios4


    【解决方案1】:

    我认为问题如下: 您的日期设置为 GMT 时区 (+0000) 如果您在美国,例如在 GTM-6,那么在 -currentCalendar 之前,第一个日期将是 8 月 3 日下午 6 点,而第二个日期将是 8 月 4 日上午 8:49。

    您应该强制您的日历使用 UTC (GMT) 时区,或者将日期放在您的时区中,这取决于您的应用程序的正确性。

    【讨论】:

    • 就是这样......正是问题所在。时区对我来说并不重要,因为我知道两者都在同一个本地时区。
    • 将日历设置为 UTC 不一定是正确的解决方案。这取决于您需要什么日期。如果您需要当地时间的日期,则不要设置日历的时区。
    【解决方案2】:

    您似乎遇到了时区问题。尽管您的日期设置在 +0000 时区,但您的 [NSCalendar calendar] 调用可能会返回您当地时区的日历。考虑到当地时间的调整,orderDate很可能在第二天。手动将日历设置为 +0000 时区。

    【讨论】:

      【解决方案3】:

      NSDate 有一个 isEqualToDate: 函数。所以你想做的事情可以通过:

      [datea isEqualToDate:dateb];
      

      还有一个 Compare: 函数可用,它返回日期的顺序。

      编辑:我现在知道这并不能回答您的问题,即为什么设置相同的日期会返回不同的值。对不起!这仍然可能有助于使您的代码更简洁。

      【讨论】:

        猜你喜欢
        • 2016-11-06
        • 1970-01-01
        • 2012-06-16
        • 2021-06-11
        • 1970-01-01
        • 2014-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多