Home > Back-end >  Formatting a Countdown Timer When Timer Reaches Negative Numbers
Formatting a Countdown Timer When Timer Reaches Negative Numbers

Time:01-01

I have an Int, this Int relates to number of minutes. I convert this Int to hours, minutes and seconds using following code and all works great until the timer is below 0.

let hours = Int(timeRemaining) / 3600
let minutes = Int(timeRemaining) / 60 % 60
let seconds = Int(timeRemaining) % 60
timeLeftLabel.text = String(format:"i:i:i", hours, minutes, seconds)

The output from the above code looks something like this and it counts down perfectly: 02:56:07

However, as soon as the time reaches 0 the format starts looking like this: -2:-56:-7 (this is obviously after minus 2 hours, it doesn't immediately jump to minus 2 hours, I'm just trying to highlight the point)

As you can see, there are numerous issues here, firstly the minus symbol, I simply want there to be one minus symbol at the start. Then the 0's are missing from hours and seconds, it should simply read: -02:56:07

The only way I can think to try and resolve this is to use: replacingOccurrences(of) but was wondering if there was a better option?

Any advice much appreciated.

CodePudding user response:

A much better solution is to use a DateComponentsFormatter

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.zeroFormattingBehavior = .pad

Example

let timeRemaining: TimeInterval = 2 * 60 * 60   56 * 60   7
let negative = -1 * timeRemaining
print(formatter.string(from: timeRemaining)!)
print(formatter.string(from: negative)!)

02:56:07
-02:56:07

CodePudding user response:

Since you just want a single negative sign in front of the whole string, start with the absolute value of your interval and do your arithmetic, and then prepend the minus sign if the original was negative.

(But I agree that it is better to use a formatter and no arithmetic.)

CodePudding user response:

Solution

you can try this code use abs() to formate signal timeLeftLabel.text = String(format:"i:i:i", hours, abs(minutes), abs(seconds))

By the way

arithmetic is not always as smooth as expected, you can try something like Formatter anyway or New Formatters supported by iOS15

reference: https://sarunw.com/posts/new-formatters-in-ios15/

  • Related