There are 4 methods for comparing dates:
isEqualToDate(anotherDate: NSDate) -> Bool
earlierDate(anotherDate: NSDate) -> NSDate
laterDate(anotherDate: NSDate) -> NSDate
compare(anotherDate: NSDate) -> NSComparisonResult
- (BOOL)isEqualToDate:(NSDate *)anotherDate
- (NSDate *)earlierDate:(NSDate *)anotherDate
- (NSDate *)laterDate:(NSDate *)anotherDate
- (NSComparisonResult)compare:(NSDate *)anotherDate
Let’s say we have 2 dates:
let date1: NSDate = ... // initialized as July 7, 2016 00:00:00
let date2: NSDate = ... // initialized as July 2, 2016 00:00:00
NSDate *date1 = ... // initialized as July 7, 2016 00:00:00
NSDate *date2 = ... // initialized as July 2, 2016 00:00:00
Then, to compare them, we try this code:
if date1.isEqualToDate(date2) {
// returns false, as both dates aren't equal
}
earlierDate: NSDate = date1.earlierDate(date2) // returns the earlier date of the two (date 2)
laterDate: NSDate = date1.laterDate(date2) // returns the later date of the two (date1)
result: NSComparisonResult = date1.compare(date2)
if result == .OrderedAscending {
// true if date1 is earlier than date2
} else if result == .OrderedSame {
// true if the dates are the same
} else if result == .OrderedDescending {
// true if date1 is later than date1
}