How to compare two NSDates: Which is more recent?
Let's assume two dates:
NSDate *date1;
NSDate *date2;
Then the following comparison will tell which is earlier/later/same:
if ([date1 compare:date2] == NSOrderedDescending) {
NSLog(@"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
NSLog(@"date1 is earlier than date2");
} else {
NSLog(@"dates are the same");
}
Please refer to the NSDate class documentation for more details.
Late to the party, but another easy way of comparing NSDate objects is to convert them into primitive types which allows for easy use of '>' '<' '==' etc
eg.
if ([dateA timeIntervalSinceReferenceDate] > [dateB timeIntervalSinceReferenceDate]) {
//do stuff
}
timeIntervalSinceReferenceDate
converts the date into seconds since the reference date (1 January 2001, GMT). As timeIntervalSinceReferenceDate
returns a NSTimeInterval (which is a double typedef), we can use primitive comparators.
In Swift, you can overload existing operators:
func > (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate
}
func < (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate
}
Then, you can compare NSDates directly with <
, >
, and ==
(already supported).
NSDate
has a compare function.
compare:
Returns an NSComparisonResult
value that indicates the temporal ordering of the receiver and another given date.
(NSComparisonResult)compare:(NSDate *)anotherDate
Parameters: anotherDate
The date with which to compare the receiver.
This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X.
Return Value:
- If the receiver and anotherDate are exactly equal to each other,
NSOrderedSame
- If the receiver is later in time than anotherDate,
NSOrderedDescending
- If the receiver is earlier in time than anotherDate,
NSOrderedAscending
.