Im trying to format an NSTimeInterval to mm:ss and I want to preserve all the leading zeros, for example "00:34"
Im doing the following:
NSTimeInterval interval = 34.56;
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = NSCalendarUnitMinute | NSCalendarUnitSecond;
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
NSString *string = [formatter stringFromTimeInterval:interval];
NSLog(@"%@", string);
But this is printing "0:34" and I need it to be "00:34"
Any Idea?
There is no built-in support for leading zeros for every component with NSDateComponentsFormatter
.
But you can do such formatting manually:
NSTimeInterval interval = 34.56;
unsigned int seconds = (unsigned int)interval;
NSString *string = [NSString stringWithFormat:@"%02u:%02u", (seconds / 60) % 60, seconds % 60];
NSLog(@"%@", string);