How to Compare Two Nsdate Objects in Objective C

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))

Objective C how to compare two date_time with the ignorance on second value

Nowadays, probably the best way is to use -[NSCalendar isDate:equalToDate:toUnitGranularity:].

BOOL datesAreEqual = [[NSCalendar currentCalendar] isDate:date1
equalToDate:date2 toUnitGranularity:NSCalendarUnitMinute];

To compare them (find out which one is more recent/late), use -[NSCalendar compareDate:toDate:toUnitGranularity:] instead.

compare two dates in objective-c

Parse stores dates as iso8601 format. This makes things very complex as Apple does not manage the format well. While the idea of the standard is awesome, until everyone plays by the same rules, anarchy rules..

I convert everything inbound from parse into usable format before attempting anything on their date time values..

Drop this into a library somewhere, and save yourself tons of headaches. This took weeks of searching and scratching to overcome.

+ (NSDate *)convertParseDate:(NSDate *)sourceDate {
NSDateFormatter *dateFormatter = [NSDateFormatter new];
NSString *input = (NSString *)sourceDate;
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
// Always use this locale when parsing fixed format date strings
NSLocale* posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.locale = posix;
NSDate *convertedDate = [dateFormatter dateFromString:input];

assert(convertedDate != nil);
return convertedDate;
}

Comparing two NSDates and ignoring the time component

You set the time in the date to 00:00:00 before doing the comparison:

unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar* calendar = [NSCalendar currentCalendar];

NSDateComponents* components = [calendar components:flags fromDate:date];

NSDate* dateOnly = [calendar dateFromComponents:components];

// ... necessary cleanup

Then you can compare the date values. See the overview in reference documentation.

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.

iOS - Comparing NSDate with another NSDate

I have found another very nice approach to do the same...
here is the code, i thought to share it with stackoverflow.
Cocoa has couple of methods for this:

in NSDate

– isEqualToDate:  
– earlierDate:
– laterDate:
– compare:

When you use - (NSComparisonResult)compare:(NSDate *)anotherDate ,you get back one of these:

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.

example:

NSDate * now = [NSDate date];
NSDate * mile = [[NSDate alloc] initWithString:@"2001-03-24 10:45:32 +0600"];
NSComparisonResult result = [now compare:mile];

NSLog(@"%@", now);
NSLog(@"%@", mile);

switch (result)
{
case NSOrderedAscending: NSLog(@"%@ is in future from %@", mile, now); break;
case NSOrderedDescending: NSLog(@"%@ is in past from %@", mile, now); break;
case NSOrderedSame: NSLog(@"%@ is the same as %@", mile, now); break;
default: NSLog(@"erorr dates %@, %@", mile, now); break;
}

[mile release];

iOS: Compare two NSDate-s without time portion


NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger comps = (NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear);

NSDateComponents *date1Components = [calendar components:comps
fromDate: date1];
NSDateComponents *date2Components = [calendar components:comps
fromDate: date2];

date1 = [calendar dateFromComponents:date1Components];
date2 = [calendar dateFromComponents:date2Components];

NSComparisonResult result = [date1 compare:date2];
if (result == NSOrderedAscending) {
} else if (result == NSOrderedDescending) {
} else {
//the same
}

There is another handy method to create for a given date the date that represents the start of a given unit: [aCalendar rangeOfUnit:startDate:interval:forDate:]

To illustrate how this method works, see this code, that easily creates the date for the beginning of the day, week, month and year for a given date (here: now).

NSDate *now = [NSDate date];
NSDate *startOfToday = nil;
NSDate *startOfThisWeek = nil;
NSDate *startOfThisMonth = nil;
NSDate *startOfThisYear = nil;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&startOfToday interval:NULL forDate:now];
[[NSCalendar currentCalendar] rangeOfUnit:NSWeekCalendarUnit startDate:&startOfThisWeek interval:NULL forDate:now];
[[NSCalendar currentCalendar] rangeOfUnit:NSMonthCalendarUnit startDate:&startOfThisMonth interval:NULL forDate:now];
[[NSCalendar currentCalendar] rangeOfUnit:NSYearCalendarUnit startDate:&startOfThisYear interval:NULL forDate:now];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setTimeStyle:NSDateFormatterFullStyle];

NSLog(@"%@", [formatter stringFromDate:now]);
NSLog(@"%@", [formatter stringFromDate:startOfToday]);
NSLog(@"%@", [formatter stringFromDate:startOfThisWeek]);
NSLog(@"%@", [formatter stringFromDate:startOfThisMonth]);
NSLog(@"%@", [formatter stringFromDate:startOfThisYear]);

result:

Thursday, July 12, 2012, 4:36:07 PM Central European Summer Time 
Thursday, July 12, 2012, 12:00:00 AM Central European Summer Time
Sunday, July 8, 2012, 12:00:00 AM Central European Summer Time
Sunday, July 1, 2012, 12:00:00 AM Central European Summer Time
Sunday, January 1, 2012, 12:00:00 AM Central European Standard Time

this allows us to shorten the first code to:

[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&date1 interval:NULL forDate:date1];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&date2 interval:NULL forDate:date2];

NSComparisonResult result = [date1 compare:date2];
if (result == NSOrderedAscending) {
} else if (result == NSOrderedDescending) {
} else {
//the same
}

Note, that in this code, date1 and date2 will be overwritten. Alternatively you can pass in a reference to another NSDate pointer for startDate as shown in the code above, where now stays untouched.

Compare two NSDates for same date/time

You're comparing two pointer values. You need to use the NSDate comparison method like:

return ([date1 compare:date2] == NSOrderedSame);


Related Topics



Leave a reply



Submit