Instead of doing all the math yourself, here's an alternate way to do unit conversions.
I also included a function for zero-padding the numbers to cut down on code repetition.
function zeroPad(number) {
return String(number).padStart(2, '0')
}
function formatTime(totalSeconds) {
const second = 1
const minute = 60*second
const hour = 60*minute
const day = 24*hour
let remainingTime = totalSeconds
const days = Math.floor(remainingTime/day)
remainingTime -= days*day
const hours = Math.floor(remainingTime/hour)
remainingTime -= hours*hour
const minutes = Math.floor(remainingTime/minute)
remainingTime -= minutes*minute
const seconds = remainingTime/second
const secondsZPad = seconds < 10 ? `0${seconds}` : seconds;
let formattedString = `${zeroPad(days)}:${zeroPad(hours)}:${zeroPad(minutes)}:${secondsZPad}`;
return formattedString;
}
console.log(formatTime(4988.75));
Semantically, multiplying a number by the defined unit (hour = 60*minute
) applies the unit to the value and dividing (for example, secondsInDay = 1*day/second
) returns the value in another unit. Under the hood, the numeric value is in units of whichever unit was assigned the value 1--second
in this case. This is best since the input to the function is already in seconds.
Granted, the last line let seconds = rest/second
is somewhat redundant since second = 1
, but it keeps with the pattern. However, if totalSeconds
could be a floating point number, the zeroPad()
function doesn't work since the length of the string is already longer than 2.