简体   繁体   中英

Calculating time difference in Objective C

I have 2 times values in NSString either in 12 hour format(10-09 PM) or 24 hour format (18-12). How to calculate time difference between two? (two dates will be either in 12 hour or 24 hour format, not mixed format)

NSDateFormatter *df=[[NSDateFormatter alloc] init];
// Set the date format according to your needs
[df setDateFormat:@"MM/dd/YYYY hh:mm a"]; //for 12 hour format
//[df setDateFormat:@"MM/dd/YYYY HH:mm "]  // for 24 hour format
NSDate *date1 = [df dateFromString:firstDateString];
NSDate *date2 = [df dateFromString:secondDatestring];
NSLog(@"%@f is the time difference",[date2 timeIntervalSinceDate:date1]);
[df release];

hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM