How to calculate time in hours between two dates in iOS

How can I calculate the time elapsed in hours between two times (possibly occurring on different days) in iOS?


Solution 1:

The NSDate function timeIntervalSinceDate: will give you the difference of two dates in seconds.

 NSDate* date1 = someDate;
 NSDate* date2 = someOtherDate;
 NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
 double secondsInAnHour = 3600;
 NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;

See, the apple reference library http://developer.apple.com/library/mac/navigation/ or if you are using Xcode just select help/documentation from the menu.

See: how-to-convert-an-nstimeinterval-seconds-into-minutes

--edit: See ÐąrέÐέvil's answer below for correctly handling daylight savings/leap seconds

Solution 2:

NSCalendar *c = [NSCalendar currentCalendar];
NSDate *d1 = [NSDate date];
NSDate *d2 = [NSDate dateWithTimeIntervalSince1970:1340323201];//2012-06-22
NSDateComponents *components = [c components:NSHourCalendarUnit fromDate:d2 toDate:d1 options:0];
NSInteger diff = components.minute;

NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit

Change needed components to day, hour or minute, which difference you want. If NSDayCalendarUnit is selected then it'll return the number of days between two dates similarly for NSHourCalendarUnit and NSMinuteCalendarUnit

Swift 4 version

let cal = Calendar.current
let d1 = Date()
let d2 = Date.init(timeIntervalSince1970: 1524787200) // April 27, 2018 12:00:00 AM
let components = cal.dateComponents([.hour], from: d2, to: d1)
let diff = components.hour!