簡體   English   中英

計算Swift中兩個日期之間的差異

[英]Calculating the difference between two dates in Swift

我已經看到許多方法如何根據特定日期組件計算兩個日期之間的差異,例如天、小時、月等(請參閱Stackoverflow 上的這個答案):

Calendar.current.dateComponents([.hour], from: fromDate, to: toDate).hour
Calendar.current.dateComponents([.day], from: fromDate, to: toDate).day
Calendar.current.dateComponents([.month], from: fromDate, to: toDate).month

我還沒有看到如何使用實際的Date對象進行計算。 就像是

func computeNewDate(from fromDate: Date, to toDate: Date) -> Date    
     let delta = toDate - fromDate
     let today = Date()
     if delta < 0 {
         return today
     } else {
         return today + delta
     }
}

我已經看到了 iOS 10 中引入的DateInterval類型,但根據文檔

[it] 不支持反向間隔,即持續時間小於 0 且結束日期早於開始日期的間隔。

這使得用日期計算本質上很困難——尤其是當您不知道哪個是較早的日期時。

是否有任何干凈整潔的方法來直接計算Date之間的時間差(並將它們再次添加到Date實例)而不用它們的timeIntervalSinceReferenceDate計算?

我最終為Date創建了一個自定義運算符:

extension Date {

    static func - (lhs: Date, rhs: Date) -> TimeInterval {
        return lhs.timeIntervalSinceReferenceDate - rhs.timeIntervalSinceReferenceDate
    }

}

使用這個運算符,我現在可以在更抽象的層次上計算兩個日期之間的差異,而無需關心timeIntervalSinceReferenceDate或參考日期究竟是什么——並且不會丟失精度,例如:

let delta = toDate - fromDate

顯然,我沒有太大變化,但對我來說,它更具可讀性和結果:Swift 已經為DateTimeInterval實現了+運算符:

 /// Returns a `Date` with a specified amount of time added to it. public static func + (lhs: Date, rhs: TimeInterval) -> Date

所以它已經支持

Date + TimeInterval = Date

因此,它還應支持

Date - Date = TimeInterval

在我看來,這就是我通過-運算符的簡單實現添加的內容。 現在我可以簡單地按照我的問題中提到的方式編寫示例函數:

func computeNewDate(from fromDate: Date, to toDate: Date) -> Date    
     let delta = toDate - fromDate // `Date` - `Date` = `TimeInterval`
     let today = Date()
     if delta < 0 {
         return today
     } else {
         return today + delta // `Date` + `TimeInterval` = `Date`
     }
}

很可能這有一些我目前不知道的缺點,我很想聽聽您對此的看法。

您可以使用自定義運算符進行擴展,並返回元組

extension Date {

    static func -(recent: Date, previous: Date) -> (month: Int?, day: Int?, hour: Int?, minute: Int?, second: Int?) {
        let day = Calendar.current.dateComponents([.day], from: previous, to: recent).day
        let month = Calendar.current.dateComponents([.month], from: previous, to: recent).month
        let hour = Calendar.current.dateComponents([.hour], from: previous, to: recent).hour
        let minute = Calendar.current.dateComponents([.minute], from: previous, to: recent).minute
        let second = Calendar.current.dateComponents([.second], from: previous, to: recent).second

        return (month: month, day: day, hour: hour, minute: minute, second: second)
    }

}

使用:

let interval = Date() - updatedDate
print(interval.day)
print(interval.month)
print(interval.hour)

簡單地toDate.timeIntervalSince(fromDate)

要在不添加任何擴展的情況下重新實現您的函數:

func computeNewDate(from fromDate: Date, to toDate: Date) -> Date  {  
     let delta = toDate.timeIntervalSince(fromDate) 
     let today = Date()
     if delta < 0 {
         return today
     } else {
         return today.addingTimeInterval(delta) 
     }
}

我找到了一個內置解決方案來計算兩個日期之間的差異。

let delta = toDate.timeIntervalSince(fromDate)

您可以使用 :

let delta = fromDate.distance(to: toDate)

比如說……

func computeNewDate(from fromDate: Date, to toDate: Date) -> Date {
    let delta = Calendar.current.dateComponents([.second], from: fromDate, to: toDate).second!
    return Calendar.current.date(byAdding: .second, value: delta, to: Date())!
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM