NSDateComponentsFormatter格式为“mm:ss”

时间:2016-10-24 20:28:53

标签: ios objective-c nsdatecomponentsformatter

我尝试将 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

任何想法?

1 个答案:

答案 0 :(得分:0)

对于NSDateComponentsFormatter的每个组件,没有内置零的内置支持。

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

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