Reputation: 443
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!
Upvotes: 2
Views: 3228
Reputation: 437937
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 (e.g., depending upon whether your calendar will “spring forward”, “fall back”, or, the vast majority of the time, not change at all).
Upvotes: 6