Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate time in hours between two dates in iOS

Tags:

ios

iphone

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

like image 499
iosrookie Avatar asked Nov 03 '10 04:11

iosrookie


People also ask

How do I calculate hours between two dates?

To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.

How do I get the time difference between two dates in Swift?

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!

How do I calculate hours between two dates in Excel?

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")


2 Answers

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

like image 152
Akusete Avatar answered Oct 12 '22 22:10

Akusete


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! 
like image 24
aahsanali Avatar answered Oct 12 '22 22:10

aahsanali