3

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?

Rudolf Adamkovič
  • 31,030
  • 13
  • 103
  • 118
  • This is crazy, but I have the exact opposite result. Using swift playgrounds with a `DateComponentsFormatter` I get `00:05`. However, I want `0:05`! – Michael Ozeryansky Dec 24 '19 at 03:53

1 Answers1

3

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

Community
  • 1
  • 1
Nikita Ivaniushchenko
  • 1,425
  • 11
  • 11