【问题标题】:How to compare two dates in iOS [duplicate]如何在iOS中比较两个日期[重复]
【发布时间】:2013-11-24 16:46:20
【问题描述】:

我想比较两个日期。这是我写的代码

NSDate *c_date=[NSDate date];

NSDate  *newDate = [c_date dateByAddingTimeInterval:300];

此代码不起作用?我缺少什么?

【问题讨论】:

  • 这个问题中的代码甚至没有尝试进行比较。

标签: ios objective-c nsdate


【解决方案1】:

从NSDate,你可以使用

- (NSComparisonResult)compare:(NSDate *)anotherDate

【讨论】:

  • if ([[NSDate date] isEqualToDate:newDate]){ NSLog(@"same"); } if ([[NSDate date] compare:newDate]==NSOrderedSame) { NSLog(@"same");但是这两个代码都不起作用..我错过了什么..请帮帮我?
  • 你在创建第二个约会时加了300,为什么会一样?
  • 编辑您的问题,使其更容易回答
【解决方案2】:

你可以使用

- (NSComparisonResult)compare:(NSDate *)other;

这将产生一个

typedef NS_ENUM(NSInteger, NSComparisonResult) {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending};

在您的示例中,您只是创建了两个具有已知 NSTimeInterval (300) 的不同 NSDate 对象,因此没有可比性。

【讨论】:

    【解决方案3】:

    使用[NSDate timeIntervalSince1970],它将返回一个简单的双精度值,可以像任何其他值一样用于比较。

    NSDate *c_date=[NSDate date];
    NSDate *newDate = [c_date dateByAddingTimeInterval:300];
    NSTimeInterval c_ti = [c_date timeIntervalSince1970];
    NSTimeInterval new_ti = [newDate timeIntervalSince1970];
    if (c_ti < new_ti) {
        // c_date is before newDate
    } else if (c_ti > new_ti) {
        // c_date is after newDate
    } else {
        // c_date and newDate are the same
    }
    

    还有[NSDate compare:]方法,你可能会觉得更方便。

    【讨论】:

      【解决方案4】:

      事情就是这样(嗯,这可能是事情,从您的问题中并不是完全 100% 清楚)。 NSDate 表示自 1970 年 1 月 1 日以来的以秒为单位的间隔。在内部,它使用浮点数(在 OS X 中为双精度,在 iOS 中不确定)。这意味着比较两个 NSDate 的相等性是干脆利落的,实际上它主要是未命中。

      如果您想确保某个日期在另一个日期的 1/2 秒以内,请尝试:

      fabs([firstDate timeIntervalSinceDate: secondDate]) < 0.5
      

      如果您只想让两个日期在同一天,则需要使用NSCalendar and date components

      另请参阅此 SO 答案。

      https://stackoverflow.com/a/6112384/169346

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-02
        • 1970-01-01
        • 1970-01-01
        • 2011-08-09
        • 2011-09-01
        • 2015-08-28
        相关资源
        最近更新 更多