【问题标题】:-[NSCalendar components:fromDate:toDate:options] always returns 0 diff-[NSCalendar components:fromDate:toDate:options] 总是返回 0 diff
【发布时间】:2012-12-24 10:13:21
【问题描述】:

我已经阅读了一些关于如何在 iOS 中计算 2 个日期之间的差异的线程,这是一个似乎也由 Apple 文档提供的示例,我用它来确定 2 个日期是否相同(忽略时间) .但是组件:方法总是返回年=0、月=0、日=0,即使两个日期不同。我不知道为什么......我会很感激你的想法......

+ (BOOL)isSameDate:(NSDate*)d1 as:(NSDate*)d2 {
if (d1 == d2) return true;
if (d1 == nil || d2 == nil) return false;

NSCalendar* currCal = [NSCalendar currentCalendar];

// messing with the timezone - can also be removed, no effect whatsoever:
NSTimeZone* tz = [NSTimeZone timeZoneForSecondsFromGMT:0];
[currCal setTimeZone:tz];

NSDateComponents* diffDateComps =
[currCal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
        fromDate:d1 toDate:d2 options:0];

return ([diffDateComps year] == 0 && [diffDateComps month] == 0 && [diffDateComps day] == 0);
}

【问题讨论】:

标签: ios nscalendar nsdatecomponents


【解决方案1】:

好的,我发现了问题,不是每个日期都发生,只有连续日期发生。事实证明,'isSameDate' 没有正确实现,因为组件:fromDate:toDate 将在 12 月 23 日 8:00、12 月 24 日 07:59 返回 0,即使时间组件不在组件标志中!但它会在 12 月 23 日 8:00、12 月 24 日 8:01 返回 1。

要修复我的方法,我需要执行其他操作:

NSDateComponents* c1 =
    [currCal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
        fromDate:d1];

NSDateComponents* c2 =
    [currCal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
        fromDate:d2];

return ([c1 day] == [c2 day] && [c1 month] == [c2 month] && [c1 year] == [c2 year]);

【讨论】:

    猜你喜欢
    • 2015-09-27
    • 2014-03-20
    • 2013-04-13
    • 2013-03-30
    • 2016-07-13
    • 2023-04-09
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多