I have a number, such as:
301
I want to convert to a time format: 00:05:01
My idea is let the 301/3600
to get the hour, (301%3600)/60
get the minute, and 301%60
get the second, I can get the format string, but if is there is a easy way to get that? Because I think this maybe not normal.
If you can live with 0:05:01
(no leading zero for hours) use (NS)DateComponentsFormatter
:
Swift:
let number = 301
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.zeroFormattingBehavior = .pad
let result = formatter.string(from: TimeInterval(number))
print(result)
ObjC:
NSInteger number = 301;
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
NSString *result = [formatter stringFromTimeInterval:(NSTimeInterval)number];
NSLog(@"%@", result);