Compare two NSDates

余生长醉 提交于 2019-12-21 12:42:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!