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 NSDateFo
To "extend" Matthias Bauch's suggestion, in Swift I would make this a computed property of NSTimeInterval:
extension NSTimeInterval {
var stringValue: String {
let interval = Int(self)
let seconds = interval % 60
let minutes = (interval / 60) % 60
let hours = (interval / 3600)
return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}
}
The advantage of this is it's attached to the NSTimeInterval
type, not your view controller or wherever else you put that function. To use you'd go something like:
let timeInterval = NSDate().timeIntervalSinceDate(start)
self.elapsedTimeLabel.text = timeInterval.stringValue
Objective C version of onmyway133's answer
- (NSString*) formatTimeInterval:(NSTimeInterval) timeInterval {
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
if (timeInterval > 3600) {
formatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
} else {
formatter.allowedUnits = NSCalendarUnitMinute | NSCalendarUnitSecond;
}
return [formatter stringFromTimeInterval:timeInterval];
}
I guess, the timer fraction should be ceiled out. As Matthias' code was creating that issue in seconds, I use the following slightly modified from that of Matthias
- (NSString *)stringFromTimeInterval:(NSTimeInterval)interval {
int ti = (int) ceil(interval);
int seconds = ti % 60;
int minutes = (ti / 60) % 60;
int hours = (ti / 3600);
return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
}
DateComponentsFormatter().string(from: <# TimeInterval #>)
ex:
DateComponentsFormatter().string(from: 59.0)
Some extra lines of code, but I feel using NSDateComponents will give a more precise value.
- (NSString *)getTimeRepresentationFromDate:(NSDate *)iDate withTimeInterval:(NSTimeInterval)iTimeInterval {
NSString *aReturnValue = nil;
NSDate *aNewDate = [iDate dateByAddingTimeInterval:iTimeInterval];
unsigned int theUnits = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSCalendar *aCalender = [NSCalendar currentCalendar];
NSDateComponents *aDateComponents = [aCalender components:theUnits fromDate:iDate toDate:aNewDate options:0];
aReturnValue = [NSString stringWithFormat:@"%d:%d:%d", [aDateComponents hour], [aDateComponents minute], [aDateComponents second]];
return aReturnValue;
}
NSTimeInterval ti = 3667;
double hours = floor(ti / 60 / 60);
double minutes = floor((ti - (hours * 60 * 60)) / 60);
double seconds = floor(ti - (hours * 60 * 60) - (minutes * 60));