I have 2 NSDate object thats shows 24hour time. Is there a way I can subtract those two times and put the result in a label. Ive searched for a method but couldn't find one. The only thing I could find was cover it to a double with timeIntervalFromDate method, which returns a double and I need the 24hour representation of that.
Asked
Active
Viewed 2,626 times
3 Answers
1
It just returns an NSTimeInterval
that is typedef double
NSTimeInterval is a representation in seconds.
Doing the math to know how may hours are in x seconds, you just need to divide the retuned interval to 3600 seconds and round the result.
I've build a simple extension to be used in swift to help in calendrical calculation, you can find it here: AFSwiftDateExtension

Andrea
- 26,120
- 10
- 85
- 131
-
I did try this and it works fine, I just have a small bug, where if its a straight hour difference its calculating 59 minutes instead – user3275730 Jun 30 '15 at 20:35
-
Probably this is beach it also takes into account milliseconds – Andrea Jul 01 '15 at 06:23
0
This function may solve your problem:
func hoursFrom(earlierDate : NSDate, laterDate:NSDate) -> Int
{
return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitHour, fromDate: earlierDate, toDate: laterDate, options: nil).hour
}
Adapted from this related question.

Community
- 1
- 1

Leonardo Yvens
- 81
- 4
0
extension NSTimeInterval {
var time:String {
return String(format:"%02d:%02d:%02d", Int((self/3600.0)%24), Int((self/60.0)%60), Int((self)%60))
}
}
println(30.time) // "00:00:30"
println(60.time) // "00:01:00"
println(600.time) // "00:10:00"
println(3600.time) // "01:00:00"

Leo Dabus
- 229,809
- 59
- 489
- 571