简体   繁体   中英

Compare DateComponents in swift

Is there any convenient way in Swift to say that, for example, 15 months is more than 1 year and 1 week is less than 10 days? I feel like DateComponents represents my needs best, so I need something like:

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

But currently in swift DateComponents are not comparable (Binary operator '>' cannot be applied to two 'DateComponents' operands), as I understand.

So maybe anyone can help me to find the solution with pure swift, or using some library? Thank you in advance!

You can create dates from the DateComponents and compare them. You can make DateComponents conform to 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)!
    }
}
    

Then you can do those comparisons:

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

You might also want to make it 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)!
    }
}

Disclaimer: This revised answer is using the current date/time as the reference to ensure meaningful comparison of days and months (give that the number of days per month can change). Questions like “are there more than 30 days in a month” only makes sense if the caller supplies a reference date or we use “now” (which is what I've done above).

Note, by using “now” as the reference date, then comparisons like “which is greater, 24 hours or 1 day” will now incorporate daylight savings (eg, depending upon whether your calendar will “spring forward”, “fall back”, or, the vast majority of the time, not change at all).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM