如何在 iPhone/iOS 中比較兩個 NSDates?


本文我們將介紹如何在 Swift 中比較兩個 NSDates。首先我們需要建立兩個 NSDates。

這次我們將在遊樂場而不是模擬器中進行。

首先我們建立兩個不同的日期。

let dateOne = NSDateComponents()
dateOne.day = 5
dateOne.month = 6
dateOne.year = 1993
let dateTwo = NSDateComponents()
dateTwo.day = 4
dateTwo.month = 2
dateTwo.year = 1995

使用這些日期元件,我們將建立日期,然後比較它們

let cal = NSCalendar.current
let FirstDate = cal.date(from: dateOne as DateComponents)
let secondDate = cal.date(from: dateTwo as DateComponents)

現在,為了比較它們,我們將使用 if 條件。

if secondDate!.compare(firstDate!) == .orderedAscending {
   print("date 1 is bigger than date 2")
} else {
   print("Date 2 is bigger")
}

以下是上面程式碼在模擬器上執行時的輸出。

我們可以有三種不同的方法來進行比較。

  • orderedAscending
  • orderedDescending
  • orderedSame

更新日期:2019-07-30

118 次瀏覽

開啟您的 職業生涯

完成本課程即可獲得認證

開始
廣告
© . All rights reserved.