Ranjit Ranjit - 1 year ago 81
iOS Question

How to compare two NSDate objects in objective C

I have objects of Date type..

So I want to compare them, and I have written a if condition in the following below way

if(([startDate1 isEqualToDate:[self getDefaultDate]]) || (startDate1 != [ self getDefaultDate] && m_selectedDate >= m_currentDate1 && cycleStopped))

///execute some condition


So whether I am right or wrong..in this approach?

One more thing whether righting this way is right

if(dtdate > [m_array objectatIndex:i]


Because I am getting a random behaviour..

So please help me out friends and geeks


Answer Source

Here's an example using the NSDate method, compare:

if([startDate compare: endDate] == NSOrderedDescending) // if start is later in time than end
    // do something

From the class reference:


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.

You could also use the timeIntervalSinceDate: method if you wanted to compare two dates and find the seconds between them, for example.


if(([startDate1 compare:[self getDefaultDate]] == NSOrderedSame) || ([startDate1 compare: [self getDefaultDate]] != NSOrderedSame && (([m_selectedDate compare: m_currentDate1] == NSOrderedDescending) || [m_selectedDate compare: m_currentDate1] == NSOrderedSame) && cycleStopped))