Checking if one NSDate is greater than another

Viewed 25140
if (datStartDate > datEndDate) {

This doesn't seem to work. I know there's a isEqual, etc., but how do I perform "is greater than"?

There are both NSDate.

7 Answers

I've been working with NSDate and NSComparison result stuff for years and I can never for the life of me remember how this works. So I wrote a convenience extension on Date for it:

func isBefore(_ otherDate: Date) -> Bool {
    let result = self.compare(otherDate)
    switch result {
    case .orderedAscending:
        return true
    case .orderedSame,
         .orderedDescending:
        return false
    }
}

If you want to have an isAfter extension it just has to return true for orderedDescending.

if ([startDate compare:endDate] == NSOrderedAscending) {
        NSLog(@"startDate is EARLIER than endDate");
}
Related