【问题标题】:Checking if one NSDate is greater than another检查一个 NSDate 是否大于另一个
【发布时间】:2011-04-19 20:17:36
【问题描述】:
if (datStartDate > datEndDate) {

这似乎不起作用。我知道有isEqual等,但是如何执行“大于”呢?

NSDate 都有。

【问题讨论】:

标签: objective-c nsdate


【解决方案1】:
if ([startDate compare:endDate] == NSOrderedAscending) {
        NSLog(@"startDate is EARLIER than endDate");
}

【讨论】:

    【解决方案2】:

    多年来,我一直在使用 NSDate 和 NSComparison 结果的东西,但我这辈子都不记得它是如何工作的。所以我在Date 上为它写了一个便利扩展:

    func isBefore(_ otherDate: Date) -> Bool {
        let result = self.compare(otherDate)
        switch result {
        case .orderedAscending:
            return true
        case .orderedSame,
             .orderedDescending:
            return false
        }
    }
    

    如果你想拥有一个isAfter 扩展,它只需要返回true 以获得orderedDescending

    【讨论】:

      【解决方案3】:

      已接受答案的 Swift 2 版本:

      if firstDate.timeIntervalSinceDate(secondDate) > 0 {
          // firstDate is greater (further in the future) than secondDate
      }
      

      【讨论】:

        【解决方案4】:

        怎么样……

        if ([datStartDate earlierDate: datEndDate] == datStartDate) {
            // datStartDate is earlier
        } else {
            // datEndDate is earlier
        }
        

        【讨论】:

        • 非常感谢 :)
        【解决方案5】:

        我知道的最简单的方法是:

        if( [firstDate timeIntervalSinceDate:secondDate] > 0 ) {
        

        其他答案包括比较:,想要添加一些味道;)。

        【讨论】:

        • 没有理由使用这个想法,因为我们有 -compare: 方法。但这个想法肯定是可行的。
        • 单线是使用它的足够大的理由。 +1。
        • 这确实具有吸引力(和风味)但我认为由于浮点计算和比较准确性问题,对于非常接近的 NSDates,它可能会返回错误的答案。最好使用“比较:”或添加更易读的语义包装器 -(BOOL) isEarlierThan: 和 -(BOOL) isLaterThan: 到现有的 -(BOOL)isEqual:
        【解决方案6】:

        正如你所拥有的NSDates

        NSDate *datStartDate = [NSDate dateWithString:@"2010-10-01 03:00:00 +0900"];
        NSDate *datEndDate   = [NSDate dateWithString:@"2010-10-01 04:00:00 +0900"];
        
        if ( ([datStartDate compare:datEndDate]) == NSOrderedDescending ) {
            ...
        }
        

        【讨论】:

        • 使用“自然语言”构造字符串现在已完全弃用,并且无法编译。
        【解决方案7】:

        要比较日期,请使用-compare: 方法:

        返回值如果:

        • 接收者和另一个日期是 完全相等, NSOrderedSame
        • 接收器稍后在 时间比另一个日期, NSOrderedDescending
        • 接收器是 时间早于另一个日期, NSOrderedAscending

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-11-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-13
          • 1970-01-01
          相关资源
          最近更新 更多