Compare Two NSDates

How can I compare two NSDates and return the amount of time between them.

For example:

2010-06-20 14:29:41 -0400 2010-06-20 14:53:29 -0400 

should return something like: 23 or 24 (minutes), rounding seconds, because I really don't need seconds.

+7
cocoa compare nsdate
source share
2 answers

try something like:

 int intervall = (int) [date1 timeIntervalSinceDate: date2] / 60; 
+11
source share

Here is a complete snippet for comparing two NSDate, which you may find more useful depending on your request.

 NSCalendar *myCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSString *str =@"12:15, 01 15 2012 AM"; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"hh:mm, dd MM yy a"]; NSDate *refDate = [formatter dateFromString:str]; NSDate *today = [NSDate date]; NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit; NSDateComponents *difference = [myCal components:unitFlags fromDate:refDate toDate:today options:0]; NSLog(@"%@",difference); 

------------------------------ what you get will be ------------ - ---------------------------

Calendar Year: 0 Month: 0 Day: 0 Hour: 1 Minute: 19

+2
source share

All Articles