Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimeInterval to HH:mm:ss?

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]?

like image 603
fuzzygoat Avatar asked Feb 08 '11 12:02

fuzzygoat


People also ask

What is NSTimeInterval?

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.

How do you convert milliseconds to seconds in Swift?

To convert milliseconds to seconds, divide the number of milliseconds by 1000 and then call the Date(timeIntervalSince1970:) with the resulting seconds.


1 Answers

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]; } 
like image 178
Matthias Bauch Avatar answered Oct 15 '22 13:10

Matthias Bauch