How can I calculate the time elapsed in hours between two times (possibly occurring on different days) in iOS?
To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.
Date Difference Extension in Swiftlet formatter = DateFormatter() formatter. dateFormat = "yyyy/MM/dd HH:mm" let xmas = formatter. date(from: "2021/12/24 00:00") let newYear = formatter. date(from: "2022/01/01 00:00") print(newYear!
Calculate hours between two times: =TEXT(B2-A2, "h") Return hours and minutes between 2 times: =TEXT(B2-A2, "h:mm") Return hours, minutes and seconds between 2 times: =TEXT(B2-A2, "h:mm:ss")
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With