Reputation: 143
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.
Upvotes: 5
Views: 415