NSDateComponentsFormatter 格式为 "mm:ss"

NSDateComponentsFormatter format to "mm:ss"

我正在尝试将 NSTimeInterval 格式化为 mm:ss,我想保留所有前导零,例如“00:34"

我正在执行以下操作:

NSTimeInterval interval = 34.56;
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = NSCalendarUnitMinute | NSCalendarUnitSecond;
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
NSString *string = [formatter stringFromTimeInterval:interval];
NSLog(@"%@", string);

但这是打印“0:34”,我需要它是“00:34

有什么想法吗?

NSDateComponentsFormatter 没有对每个组件的前导零的内置支持。

但是您可以手动进行这样的格式化:

NSTimeInterval interval = 34.56;
unsigned int seconds = (unsigned int)interval;
NSString *string = [NSString stringWithFormat:@"%02u:%02u", (seconds / 60) % 60, seconds % 60];
NSLog(@"%@", string);