【问题标题】:How do I determine whether an NSDate (including time) has passed如何确定 NSDate(包括时间)是否已过
【发布时间】:2012-02-03 11:38:09
【问题描述】:

如何确定 NSDate(包括时间)是否已过?我基本上需要将今天的日期与数据库中的日期进行比较,但我很难过。

【问题讨论】:

    标签: iphone objective-c cocoa-touch nsdate


    【解决方案1】:

    试试这个:

    if ([someDate timeIntervalSinceNow] < 0.0) {
        // Date has passed
    }
    

    【讨论】:

    • 我把它放到了一个类别方法中,这样你就可以使用someDate.isInPast
    • 您的代码只比较日期而不是时间。就像我在比较同一天但不同的时间:2015 年 1 月 1 日 5:00:00 和 2015 年 1 月 1 日 7:00:00 与此日期,它向我显示日期已过。
    • +爸爸,不明白你的意思。根据文档,此方法应该是完美的:“日期对象与当前日期和时间之间的时间间隔。(只读)如果日期对象早于当前日期和时间,则此属性的值为负数。”
    • 用于日期扩展:func isPast() -&gt; Bool { if (self.timeIntervalSinceNow &lt; 0.0) { return true } else { return false } }
    【解决方案2】:

    你可以使用

    [NSDate date];
    

    获取表示当前时间和日期的 NSDate 对象。

    然后将其与您正在分析的日期进行比较,例如:

    if ([currentDate timeIntervalSince1970] > [yourDate timeIntervalSince1970]) {
    // yourDate is in the past
    }
    

    您可以使用它来比较任意两个日期。希望这会有所帮助。

    【讨论】:

    • 或内联:([[NSDate date] timeIntervalSince1970] > [yourDate timeIntervalSince1970])
    • 我只是为比较日期提供了一个更通用的解决方案 - 将日期与现在进行比较是一个小众案例。但在实践中,您可能只会在此特定场景中使用 timeIntervalSinceNow。
    【解决方案3】:

    您需要使用 NSDate 比较,这里的许多答案都会对您有所帮助。

    iOS: Compare two dates

    逻辑需要调整,但这应该会让你朝着正确的方向前进:

    - (BOOL)date:(NSDate*)date isBefore:(BOOL)before otherDate:(NSDate*)otherDate ;
    {
        if(before && ([date compare:otherDate] == NSOrderedAscending))
            return YES;
        if (!before && ([date compare:otherDate] == NSOrderedDescending))
            return YES;  
    }
    

    用法:

    if([self date:yourDate isBefore:YES otherDate:[NSDate date]]) 
    

    【讨论】:

    • 在编码风格的注释中:你的第二个参数应该真正命名为isBefore:。大声朗读“date:X isBefore:YES/NO otherDate:Y”听起来比“date:X is:YES/NO otherDate:Y”好得多。
    猜你喜欢
    • 1970-01-01
    • 2011-01-20
    • 2015-06-12
    • 1970-01-01
    • 2010-10-31
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多