如何在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP