Swift 3 - Comparing Date objects
I have tried this snippet (in Xcode 8 Beta 6), and it is working fine.
let date1 = Date()
let date2 = Date().addingTimeInterval(100)
if date1 == date2 { ... }
else if date1 > date2 { ... }
else if date1 < date2 { ... }
Date
is Comparable
& Equatable
(as of Swift 3)
This answer complements @Ankit Thakur's answer.
Since Swift 3 the Date
struct (based on the underlying NSDate
class) adopts the Comparable
and Equatable
protocols.
Comparable
requires thatDate
implement the operators:<
,<=
,>
,>=
.Equatable
requires thatDate
implement the==
operator.Equatable
allowsDate
to use the default implementation of the!=
operator (which is the inverse of theEquatable
==
operator implementation).
The following sample code exercises these comparison operators and confirms which comparisons are true with print
statements.
Comparison function
import Foundation
func describeComparison(date1: Date, date2: Date) -> String {
var descriptionArray: [String] = []
if date1 < date2 {
descriptionArray.append("date1 < date2")
}
if date1 <= date2 {
descriptionArray.append("date1 <= date2")
}
if date1 > date2 {
descriptionArray.append("date1 > date2")
}
if date1 >= date2 {
descriptionArray.append("date1 >= date2")
}
if date1 == date2 {
descriptionArray.append("date1 == date2")
}
if date1 != date2 {
descriptionArray.append("date1 != date2")
}
return descriptionArray.joined(separator: ", ")
}
Sample Use
let now = Date()
describeComparison(date1: now, date2: now.addingTimeInterval(1))
// date1 < date2, date1 <= date2, date1 != date2
describeComparison(date1: now, date2: now.addingTimeInterval(-1))
// date1 > date2, date1 >= date2, date1 != date2
describeComparison(date1: now, date2: now)
// date1 <= date2, date1 >= date2, date1 == date2