How to compare two NSDate objects in objective C
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:
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.
You could also use the timeIntervalSinceDate:
method if you wanted to compare two dates and find the seconds between them, for example.
EDIT:
if(([startDate1 compare:[self getDefaultDate]] == NSOrderedSame) || ([startDate1 compare: [self getDefaultDate]] != NSOrderedSame && (([m_selectedDate compare: m_currentDate1] == NSOrderedDescending) || [m_selectedDate compare: m_currentDate1] == NSOrderedSame) && cycleStopped))
I must admit that I find the "compare" == NSWhatHaveYou business too complicated to remember (even though it's correct and it works). NSDate has two other methods that my brain finds much easier to deal with: earlierDate and laterDate.
Consider this:
if ([myDate laterDate:today] == myDate) {
NSLog(@"myDate is LATER than today");
} else {
NSLog(@"myDate is EARLIER than today");
}
// likewise:
if ([myDate earlierDate:today] == myDate) {
NSLog(@"myDate is EARLIER than today");
} else {
NSLog(@"myDate is LATER than today");
}
Either method returns an NSDate object, which is either earlier or later than the other.
http://pinkstone.co.uk/how-to-compare-two-nsdates/
Easy way to compare NSDates (found here http://webd.fr/637-comparer-deux-nsdate):
#import <Foundation/Foundation.h>
@interface NSDate (Compare)
-(BOOL) isLaterThanOrEqualTo:(NSDate*)date;
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date;
-(BOOL) isLaterThan:(NSDate*)date;
-(BOOL) isEarlierThan:(NSDate*)date;
//- (BOOL)isEqualToDate:(NSDate *)date; already part of the NSDate API
@end
And the implementation:
#import "NSDate+Compare.h"
@implementation NSDate (Compare)
-(BOOL) isLaterThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedAscending);
}
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedDescending);
}
-(BOOL) isLaterThan:(NSDate*)date {
return ([self compare:date] == NSOrderedDescending);
}
-(BOOL) isEarlierThan:(NSDate*)date {
return ([self compare:date] == NSOrderedAscending);
}
@end
Simple to use:
if([aDateYouWant ToCompare isEarlierThanOrEqualTo:[NSDate date]]) // [NSDate date] is now
{
// do your thing ...
}
Enjoy
I really liked Luke's answer, and it worked like a charm.
I used something like this:
If ([enteredDate compare: [NSDate Date]]== NSOrderedSame || NSOrderedDescending)
{
//Do Something if the enteredDate is later or the same as today
}else
{
//if the enteredDate is before today's date
}
I'm not sure if that helps, but just to reiterate what Luke had written.