How can I calculate the time elapsed in hours between two times (possibly occurring on different days) in iOS?
-
1Another option is to use `NSCalendar`'s [`-components:fromDate:toDate:options:`](http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/Reference/NSCalendar.html) method. – Thomas Müller Nov 03 '10 at 05:38
-
I don't believe this will give you an absolute number of hours. It will only give you a value from 0-24, where you have to rely on the components Day, Month, and Year to get the full time interval. – codeperson Jan 11 '12 at 23:56
-
I tested this, and it does work just fine. With fromDate 1/Jan/2012 and toDate 4/Jan/2012 this returned 96 hours. – Thomas Müller Jan 13 '12 at 22:29
-
post your code Thomas? It doesn't work for some. – John Riselvato May 24 '12 at 20:22
5 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
-
2And what happens if the dates / times cross the transition for Daylight Savings? – Abizern Feb 08 '13 at 10:19
-
2@Abizern: Thanks, I wasn't considering those cases when I answered the question. I've linked to the answer by ÐąrέÐέvil – Akusete Feb 10 '13 at 22:25
-
i have time slot like 4:50:30 , h:m:s i have to subtract this time from 12:30:20 how i will do this – AyAz Apr 19 '16 at 07:52
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!

- 3,537
- 23
- 21
-
What value dateWithTimeIntervalSince1970 accept ? i believe you have convert 2012-06-22 date to 1340323201. please correct me. – Jeet Aug 21 '12 at 09:19
-
Not working for me. Got diff value as 9223372036854775807. Is it in milliseconds? – Kirti Nikam Aug 02 '17 at 09:06
-
-(NSMutableString*) timeLeftSinceDate: (NSDate *) dateT {
NSMutableString *timeLeft = [[NSMutableString alloc]init];
NSDate *today10am =[NSDate date];
NSInteger seconds = [today10am timeIntervalSinceDate:dateT];
NSInteger days = (int) (floor(seconds / (3600 * 24)));
if(days) seconds -= days * 3600 * 24;
NSInteger hours = (int) (floor(seconds / 3600));
if(hours) seconds -= hours * 3600;
NSInteger minutes = (int) (floor(seconds / 60));
if(minutes) seconds -= minutes * 60;
if(days) {
[timeLeft appendString:[NSString stringWithFormat:@"%ld Days", (long)days*-1]];
}
if(hours) {
[timeLeft appendString:[NSString stringWithFormat: @"%ld H", (long)hours*-1]];
}
if(minutes) {
[timeLeft appendString: [NSString stringWithFormat: @"%ld M",(long)minutes*-1]];
}
if(seconds) {
[timeLeft appendString:[NSString stringWithFormat: @"%lds", (long)seconds*-1]];
}
return timeLeft;
}

- 13,684
- 11
- 87
- 116

- 332
- 2
- 7
-
9No, do not do this. Not all hours have 3600 seconds. Not all days have 24 hours. – rmaddy May 26 '15 at 21:39
-
5This is totally wrong. Does not account for leap seconds, daylight time savings. Please don't reinvent the wheel just use the APIs provided with iOS like NSDateComponents. – Juan Catalan May 26 '15 at 21:42
Checkout : It takes care of daylight saving, leap year as it used iOS calendar to calculate. You can change the string and conditions to includes minutes with hours and days.
+(NSString*)remaningTime:(NSDate*)startDate endDate:(NSDate*)endDate {
NSDateComponents *components;
NSInteger days;
NSInteger hour;
NSInteger minutes;
NSString *durationString;
components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute
fromDate: startDate toDate: endDate options: 0];
days = [components day];
hour = [components hour];
minutes = [components minute];
if (days > 0) {
if (days > 1) {
durationString = [NSString stringWithFormat:@"%d days", days];
}
else {
durationString = [NSString stringWithFormat:@"%d day", days];
}
return durationString;
}
if (hour > 0) {
if (hour > 1) {
durationString = [NSString stringWithFormat:@"%d hours", hour];
}
else {
durationString = [NSString stringWithFormat:@"%d hour", hour];
}
return durationString;
}
if (minutes > 0) {
if (minutes > 1) {
durationString = [NSString stringWithFormat:@"%d minutes", minutes];
}
else {
durationString = [NSString stringWithFormat:@"%d minute", minutes];
}
return durationString;
}
return @"";
}

- 51,713
- 20
- 123
- 112

- 11,305
- 5
- 36
- 34
-
it is not showing more than 12 hours difference . if i want to check some conditions at 23 hours , then how to get 23 hours difference between times ? – Moxarth Jul 19 '17 at 13:17
For those who use swift 3 and above,
let dateString1 = "2018-03-15T14:20:00.000Z"
let dateString2 = "2018-03-20T14:20:00.000Z"
let Dateformatter = DateFormatter()
Dateformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date1 = Dateformatter.date(from: dateString1)
let date2 = Dateformatter.date(from: dateString2)
let distanceBetweenDates: TimeInterval? = date2?.timeIntervalSince(date1!)
let secondsInAnHour: Double = 3600
let secondsInDays: Double = 86400
let secondsInWeek: Double = 604800
let hoursBetweenDates = Int((distanceBetweenDates! / secondsInAnHour))
let daysBetweenDates = Int((distanceBetweenDates! / secondsInDays))
let weekBetweenDates = Int((distanceBetweenDates! / secondsInWeek))
print(weekBetweenDates,"weeks")//0 weeks
print(daysBetweenDates,"days")//5 days
print(hoursBetweenDates,"hours")//120 hours

- 509
- 4
- 8