If I have an NSTimeInterval that is set to say 200.0, is there a way to convert that into 00:03:20, I was thinking I could initialise an NSDate with it and then use NSDateFormatter using HH:mm:ss. My question is, is there a quick way to do this or do I have to break up the number myself and use [NSString stringWithFormat: %02d:%02d:%02d, myHour, myMin, mySec]
?
A NSTimeInterval value is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years. On its own, a time interval does not specify a unique point in time, or even a span between specific times.
To convert milliseconds to seconds, divide the number of milliseconds by 1000 and then call the Date(timeIntervalSince1970:) with the resulting seconds.
No need to use NSDateFormatter
or anything else than division and modulo. NSTimeInterval
is just a double containing seconds.
Swift
func stringFromTimeInterval(interval: NSTimeInterval) -> String { let interval = Int(interval) let seconds = interval % 60 let minutes = (interval / 60) % 60 let hours = (interval / 3600) return String(format: "%02d:%02d:%02d", hours, minutes, seconds) }
Objective-C
- (NSString *)stringFromTimeInterval:(NSTimeInterval)interval { NSInteger ti = (NSInteger)interval; NSInteger seconds = ti % 60; NSInteger minutes = (ti / 60) % 60; NSInteger hours = (ti / 3600); return [NSString stringWithFormat:@"%02ld:%02ld:%02ld", (long)hours, (long)minutes, (long)seconds]; }
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