问题
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 the seconds because I don't really need the seconds.
回答1:
try something like:
int intervall = (int) [date1 timeIntervalSinceDate: date2] / 60;
回答2:
Here the complete snippet to compare two NSDate which you may find more useful based on your query.
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 will get is -----------------------------------------
Calendar Year: 0 Month: 0 Day: 0 Hour: 1 Minute: 19
来源:https://stackoverflow.com/questions/3080535/compare-two-nsdates