I have two dates and I want to compare it.
How can I compare dates?
I have to date objects. Say modificateionDate
older updatedDate
.
So which is the best practice to compare dates?
I have two dates and I want to compare it.
How can I compare dates?
I have to date objects. Say modificateionDate
older updatedDate
.
So which is the best practice to compare dates?
Date
now conforms to Comparable
protocol. So you can simply use <
, >
and ==
to compare two Date
type objects.
if modificateionDate < updatedDate {
//modificateionDate is less than updatedDate
}
Per @NiravD's answer, Date
is Comparable
. However, if you want to compare to a given granularity, you can use Calendar
's compare(_:to:toGranularity:)
Example…
let dateRangeStart = Date()
let dateRangeEnd = Date().addingTimeInterval(1234)
// Using granularity of .minute
let order = Calendar.current.compare(dateRangeStart, to: dateRangeEnd, toGranularity: .minute)
switch order {
case .orderedAscending:
print("\(dateRangeEnd) is after \(dateRangeStart)")
case .orderedDescending:
print("\(dateRangeEnd) is before \(dateRangeStart)")
default:
print("\(dateRangeEnd) is the same as \(dateRangeStart)")
}
> 2017-02-17 10:35:48 +0000 is after 2017-02-17 10:15:14 +0000
// Using granularity .hour
let order = Calendar.current.compare(dateRangeStart, to: dateRangeEnd, toGranularity: .hour)
> 2017-02-17 10:37:23 +0000 is the same as 2017-02-17 10:16:49 +0000
Swift iOS 8 and up When you need more than simply bigger or smaller date comparisons. For example is it the same day or the previous day,...
Note: Never forget the timezone. Calendar timezone has a default, but if you do not like the default, you have to set the timezone yourself. To know which day it is, you need to know in which timezone you are asking.
extension Date {
func compareTo(date: Date, toGranularity: Calendar.Component ) -> ComparisonResult {
var cal = Calendar.current
cal.timeZone = TimeZone(identifier: "Europe/Paris")!
return cal.compare(self, to: date, toGranularity: toGranularity)
}
}
Use it like this:
if thisDate.compareTo(date: Date(), toGranularity: .day) == .orderedDescending {
// thisDate is a previous day
}
For a more complex example how to use this in a filter see this:
https://stackoverflow.com/a/45746206/4946476
Swift has ComparisonResult with orderedAscending, orderedDescending and same as below.
if modificateionDate.compare(updatedDate) == ComparisonResult.orderedAscending {
//Do what you want
}
Hope this may help you.