如何在 iOS 中獲取兩個日期之間的差異?
獲取兩個日期之間的差異很容易。你需要知道如何在日期之間做遊戲。
我們將使用 DateFormatter 類來格式化日期。
NSDate 物件的 DateFormatter 例項會建立字串表示形式,並將日期和時間的文字表示形式轉換為 NSDate 物件。
你可以在這裡閱讀更多資訊
https://developer.apple.com/documentation/foundation/dateformatter
我們還將使用 Calendar 結構,Apple 提供了其精美的文件,
https://developer.apple.com/documentation/foundation/calendar
讓我們開始吧。
開啟 Xcode,新建 Playground。
複製以下程式碼
import UIKit // create object of DateFormatter and Calendar let formatter = DateFormatter() let calendar = Calendar.current // specify the format, formatter.dateFormat = "dd-MM-yyyy" // specify the start date let startDate = formatter.date(from: "10-08-2018") // specify the end date let endDate = formatter.date(from: "23-09-2019") print(startDate!) print(endDate!) let diff = calendar.dateComponents([.day], from: startDate!, to: endDate!) // print the diff between the two dates print(diff)
廣告