Naz Naz - 6 months ago 18
iOS Question

iOS: Compare two dates

I have a

NSDate
that I must compare with other two
NSDate
and I try with
NSOrderAscending
and
NSOrderDescending
but if my date is equal at other two dates?

Example: if I have a
myDate = 24/05/2011
and other two that are one =
24/05/2011
and two
24/05/2011
what can I use?

Answer

According to Apple documentation of NSDate 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

The receiver is later in time than anotherDate, NSOrderedDescending

The receiver is earlier in time than anotherDate, NSOrderedAscending

In other words:

if ([date1 compare:date2] == NSOrderedSame) ...

Note that it might be easier in your particular case to read and write this :

if ([date2 isEqualToDate:date2]) ...

See Apple Documentation about this one.