3

I'm working on a timer in swift and came across a weird behavior for the DateComponentsFormatter when trying to format it to .zeroFormattingBehavior = .pad

func timerString(duration:Int, style: DateComponentsFormatter.UnitsStyle = .positional) -> String {
var durationFormat: DateComponentsFormatter {
    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = style
    formatter.allowedUnits = [.minute, .second]
    //formatter.zeroFormattingBehavior = .pad
    return formatter
}
return durationFormat.string(from: TimeInterval(duration)) ?? "0"
}

As long as I don't use the .zeroFormattingBehavior it outputs everything just fine - a negative duration outputs a String with a leading -. But as soon as I uncomment that line of code, the leading minus disappears. Only when it gets to more than 60 seconds, the minus is displayed again. Has anyone else experience this issue and found a solution? Somehow it seems like only minutes are used for calculating the sign.

Of course I can add the - manually if duration is between 0 and -59, but somehow this doesn't seem right.

  • Did you find any solution for this? seems like this question has been ignored by everyone. – Ramandeep Singh Gosal Dec 02 '21 at 01:28
  • No, i didn't find a "right" solution for it yet. Solved it by outputting with `if duration >= 0 || duration <= -60 { return durationFormat.string(from: TimeInterval(duration)) ?? "0" } else { return "-" + (durationFormat.string(from: TimeInterval(duration)) ?? "0") }` – JacquesNorris Dec 08 '21 at 08:06
  • I stumbled on exactly the same issue here – Joris Mans May 24 '23 at 07:43

0 Answers0