Calculate minutes between two dates

Hi,


From an API I'll get a datetime in the format 2015-09-25T09:45:00+02:00.

What can I do calculate the minutes between the current datetime and the datetime from the API.


This is what I have, but didn't work:

(...)
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss"];
NSDate *lastDate = [format dateFromString:beginTijden[0]];
NSDate *todaysDate = [NSDate date];
NSTimeInterval lastDiff = [lastDate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [todaysDate timeIntervalSinceNow];
NSTimeInterval dateDiff = lastDiff - todaysDiff;
(...)


Please help me.


Thanks 🙂

Accepted Answer

Assuming that "beginTijden[0]" is the date string "2015-09-25T09:45:00+02:00" there are two errors.

1) (I think) you need to account for the "+02:00" at the end. You may wantto include that into your format string if it means something relevant regarding what real time it is (e.g. 2 hours past UDT) - I am not sure. Or you could just delete it with:

beginTijden[0]=[beginTijden[0] substringToIndex:17];

2) the method timeIntervalSinceNow does all the work. all you need is:

NSDateFormatter *format = [[NSDateFormatter alloc] init]; 
[format setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss"]; 
beginTijden[0]=[beginTijden[0] substringToIndex:17];              
NSDate *lastDate = [format dateFromString:beginTijden[0]]; 

NSTimeInterval lastDiff = [lastDate timeIntervalSinceNow]; 

double theMinutes = lastDiff/60.0;

First up, if you’re going to deal with fixed format dates you need to use the date formatter in a very specific way. See QA1480 NSDateFormatter and Internet Dates for details.

Second, what do you mean by “minutes between”? Are you talking about the elapsed time? Or the difference between the hands on the clock? These can be different in the face of daylight savings transitions. For example, on the days that clocks go forwards, 01:59 and 03:01 are two minutes apart, but the clock faces show a 62 minute difference.

Calculating elapsed time is easy: just subtract the time intervals (with the fixes provided by PBK). Calculating clock differences is trickier.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Thanks for you help ! 🙂

Calculate minutes between two dates
 
 
Q