【问题标题】:Check if date is before current date (Swift)检查日期是否早于当前日期(Swift)
【发布时间】:2015-01-04 14:37:09
【问题描述】:

我想通过将 NSDate 与当前日期进行比较来检查 NSDate 是否早于(过去)。我该怎么做?

谢谢

【问题讨论】:

  • 显示您已经尝试解决的问题。

标签: ios swift xcode cocoa-touch nsdate


【解决方案1】:

从 Swift 3 开始,日期是可比较的

if date1 < date2 { // do something }

它们也具有可比性,因此您可以根据需要与 == 进行比较。

请参阅Paul Hudson's Article

【讨论】:

    【解决方案2】:

    这是 Swift 中的一个扩展,用于检查日期是否已过。

    extension Date {
        var isPastDate: Bool {
            return self < Date()
        }
    }
    

    用法:

    let someDate = Date().addingTimeInterval(1)
    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
        print(date.isPastDate)
    }
    

    【讨论】:

      【解决方案3】:

      在 Swift5 中

          let nextDay = Calendar.current.date(byAdding: .day, value: -1, to: Date())
          let toDay = Date()
          print(toDay)
          print(nextDay!)
      
          if nextDay! < toDay  {
              print("date1 is earlier than date2")
          }
      
      
          let nextDay = Calendar.current.date(byAdding: .month, value: 1, to: Date())
          let toDay = Date()
          print(toDay)
          print(nextDay!)
      
          if nextDay! >= toDay  {
              print("date2 is earlier than date1")
          }
      

      【讨论】:

        【解决方案4】:

        我找到了earlierDate 方法。

        if date1.earlierDate(date2).isEqualToDate(date1)  {
             print("date1 is earlier than date2")
        }
        

        您还有laterDate 方法。

        Swift 3 到 Swift 5:

        if date1 < date2  {
             print("date1 is earlier than date2")
        }
        

        【讨论】:

        • 谢谢,我去看看。
        • 这似乎返回一个日期而不是一个布尔值
        • swift3 使它更简单:只需使用
        • 难道那些方法已经不存在了?
        • 第二个在swift 5下依然有效
        【解决方案5】:

        在 Swift 4 中,您可以使用此代码

        if endDate.timeIntervalSince(startDate).sign == FloatingPointSign.minus {
            // endDate is in past
        }
        

        【讨论】:

          【解决方案6】:

          如果您需要在不创建新 Date 对象的情况下将一个日期与现在进行比较,您可以在 Swift 3 中简单地使用它:

          if (futureDate.timeIntervalSinceNow.sign == .plus) {
              // date is in future
          }
          

          if (dateInPast.timeIntervalSinceNow.sign == .minus) {
              // date is in past
          }
          

          【讨论】:

          • 这应该是公认的答案,更具可读性和意义
          • 同意@Amma。这个答案对我来说效果最好。
          【解决方案7】:

          用它制作了一个快速的 Swift 2.3 函数

          // if you omit last parameter you comare with today
          // use "11/20/2016" for 20 nov 2016
          func dateIsBefore(customDate:String, referenceDate:String="today") -> Bool {
          
              let dateFormatter = NSDateFormatter()
              dateFormatter.dateFormat = "MM/dd/yyyy"
          
              let myDate = dateFormatter.dateFromString(customDate)
              let refDate = referenceDate == "today"
                  ? NSDate()
                  : dateFormatter.dateFromString(referenceDate)
          
              if NSDate().compare(myDate!) == NSComparisonResult.OrderedDescending {
                  return false
              } else {
                  return true
              }
          }
          

          像这样使用它来查看您的日期是否早于今天的日期

          if dateIsBefore("12/25/2016") {
              print("Not Yet Christmas 2016 :(")
          } else {
              print("Christmas Or Later!")
          }
          

          或带有自定义参考日期

          if dateIsBefore("12/25/2016", referenceDate:"12/31/2016") {
              print("Christmas comes before new years!")
          } else {
              print("Something is really wrong with the world...")
          }
          

          【讨论】:

            【解决方案8】:

            有一种简单的方法可以做到这一点。 (Swift 3 更简单,在答案末尾查看)

            Swift 代码:

            if myDate.timeIntervalSinceNow.isSignMinus {
                //myDate is earlier than Now (date and time)
            } else {
                //myDate is equal or after than Now (date and time)
            }
            

            如果您需要比较没有时间的日期(“MM/dd/yyyy”)。

            Swift 代码:

            //Ref date
            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "MM/dd/yyyy"
            let someDate = dateFormatter.dateFromString("03/10/2015")
            
            //Get calendar
            let calendar = NSCalendar.currentCalendar()
            
            //Get just MM/dd/yyyy from current date
            let flags = NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear
            let components = calendar.components(flags, fromDate: NSDate())
            
            //Convert to NSDate
            let today = calendar.dateFromComponents(components)
            
            if someDate!.timeIntervalSinceDate(today!).isSignMinus {
                //someDate is berofe than today
            } else {
                //someDate is equal or after than today
            } 
            

            Apple 文档链接 here.

            编辑 1:重要

            来自 Swift 3 migration notes:

            迁移器是保守的,但 NSDate 的一些用途在 Swift 3 中有更好的表示:
            (x as NSDate).earlierDate(y) 可以更改为 x &lt; y ? x : y
            (x as NSDate).laterDate(y) 可以更改为 x &lt; y ? y : x

            因此,在 Swift 3 中,您可以使用比较运算符。

            【讨论】:

              【解决方案9】:

              您不需要在这里扩展 NSDate,只需使用 docs 中所示的“比较”即可。

              例如,在 Swift 中:

              if currentDate.compare(myDate) == NSComparisonResult.OrderedDescending {
                  println("myDate is earlier than currentDate")
              }
              

              【讨论】:

              • 您能否详细说明一下像我这样的菜鸟,在此之前您是如何设置 myDate 变量的?它是否必须以特定方式使用,是否为 INT?非常期待您的反馈。
              • @MichelKapelle myDateNSDate 的一个实例。检查 nick 添加的链接,您会在文档中看到:func compare(_ other: NSDate) -&gt; NSComparisonResult,因此:othermyDate
              【解决方案10】:

              您可以扩展NSDate 以符合EquatableComparable 协议。这些是 Swift 中的比较协议,允许熟悉的比较运算符(==、 等)处理日期。将以下内容放入适当命名的文件中,例如NSDate+Comparison.swift 在你的项目中:

              extension NSDate: Equatable {}
              extension NSDate: Comparable {}
              
              public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
                  return lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970
              }
              
              public func <(lhs: NSDate, rhs: NSDate) -> Bool {
                  return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970
              }
              

              现在您可以使用标准比较运算符检查一个日期是否在另一个日期之前。

              let date1 = NSDate(timeIntervalSince1970: 30)
              let date2 = NSDate()
              
              if date1 < date2 {
                  print("ok")
              }
              

              有关 Swift 扩展的信息,请参阅here。有关 Equatable 和 Comparable 协议的信息,请分别参见 herehere

              注意:在这种情况下,我们没有创建自定义运算符,只是扩展现有类型以支持现有运算符。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2017-07-30
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2023-03-19
                相关资源
                最近更新 更多