Hey,
I've already tried with NSDate but with no luck. I want the difference between for example 14:10 and 18:30.
Hours and minutes.
I Hope you can help me shouldn't be that complicated :)
Hey,
I've already tried with NSDate but with no luck. I want the difference between for example 14:10 and 18:30.
Hours and minutes.
I Hope you can help me shouldn't be that complicated :)
The NSDate class has a method timeIntervalSinceDate that does the trick.
NSTimeInterval secondsBetween = [firstDate timeIntervalSinceDate:secondDate];
NSTimeInterval is a double that represents the seconds between the two times.
Here's my quick solution:
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:@"HH:mm"];
NSDate *date1 = [df dateFromString:@"14:10"];
NSDate *date2 = [df dateFromString:@"18:09"];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
int hours = (int)interval / 3600; // integer division to get the hours part
int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
NSString *timeDiff = [NSString stringWithFormat:@"%d:%02d", hours, minutes];
This code works great. Only one exception. What if you want to find the difference between 23:30 and 02:30? The current code returns a -21:00. Is there a way to maybe add 24 hours (86400) to the result? I've been trying but I can't find the solution.
There's no need to calculate this by hand, take a look at NSCalendar
. If you want to get the hours and minutes between two dates, use something like this:
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *components = [gregorianCalendar components:unitFlags
fromDate:firstDate
toDate:otherDate
options:0];
[gregorianCalendar release];
You now have the hours and minutes as NSDateComponents and can access them as NSIntegers
like [components hour]
and [components minute]
. This will also work for hours between days, leap years and other fun stuff.
The Gregorian solution is very nice, clean and elegant. Thank YOu