簡體   English   中英

比較 swift 中的 DateComponents

[英]Compare DateComponents in swift

Swift有沒有方便的說法,比如15個月大於1年,1周小於10天? 我覺得DateComponents最能代表我的需求,所以我需要這樣的東西:

DateComponents(year: 1) > DateComponents(month: 15) // => false
DateComponents(day: 10) > DateComponents(weekOfMonth: 1) // => true

但據我了解,目前在 swift DateComponents 中不可比較(二元運算符“>”不能應用於兩個“DateComponents”操作數)。

所以也許任何人都可以幫助我找到純 swift 或使用某些庫的解決方案? 先感謝您!

您可以從DateComponents創建日期並比較它們。 您可以使DateComponents符合Comparable

extension DateComponents: Comparable {
    public static func < (lhs: DateComponents, rhs: DateComponents) -> Bool {
        let now = Date()
        let calendar = Calendar.current
        return calendar.date(byAdding: lhs, to: now)! < calendar.date(byAdding: rhs, to: now)!
    }
}
    

然后你可以做這些比較:

DateComponents(year: 1) > DateComponents(month: 15) // => false
DateComponents(day: 10) > DateComponents(weekOfMonth: 1) // => true

您可能還想讓它Equatable

extension DateComponents: Equatable {
    public static func == (lhs: DateComponents, rhs: DateComponents) -> Bool {
        let now = Date()
        let calendar = Calendar.current
        return calendar.date(byAdding: lhs, to: now)! == calendar.date(byAdding: rhs, to: now)!
    }
}

免責聲明:此修改后的答案使用當前日期/時間作為參考,以確保對天數和月份進行有意義的比較(假設每個月的天數可以更改)。 只有當來電者提供參考日期或我們使用“現在”(這是我在上面所做的)時,“一個月中是否有超過 30 天”這樣的問題才有意義。

請注意,通過使用“現在”作為參考日期,那么像“24 小時或 1 天哪個更大”這樣的比較現在將包含夏令時(例如,取決於您的日歷是否會“提前”、“后退”、或者,絕大多數時候,根本沒有改變)。

暫無
暫無

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

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