Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format to MM:SS using NSDateComponentsFormatter

I'm trying to format to MM:SS using NSDateComponentsFormatter:

let formatter = NSDateComponentsFormatter()

formatter.zeroFormattingBehavior = .Pad
formatter.allowedUnits = .CalendarUnitMinute | .CalendarUnitSecond

let time: NSTimeInterval = 5
let timeText = formatter.stringFromTimeInterval(time)

The problem is, that even though I specified .Pad, the result is 0:05 instead of 00:05.

Here's the relevant piece from Apple's documentation:

static var Pad: NSDateComponentsFormatterZeroFormattingBehavior { get } 
// Off: "1:0:10", On: "01:00:10" 

I've tried to add .CalendarUnitHour just to try it and got H:MM:SS instead of HH:MM:SS despite what the documentation says.

How can I pad the very first number as shown in the documentation?

like image 393
Rudolf Adamkovič Avatar asked May 30 '26 06:05

Rudolf Adamkovič


1 Answers

Sorry for wrong initial answer, there is no way to add leading zeros to hours:

When days, hours, minutes, and seconds are allowed, the value is displayed as “0d 1:00:00” using the positional style, and as “0d 1h 0m 0s” using the abbreviated style.

If you simply need to format NSTimeInterval into string like HH:MM:SS check this answer

like image 78
Nikita Ivaniushchenko Avatar answered Jun 01 '26 06:06

Nikita Ivaniushchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!