Convert seconds to hh:mm:ss in JavaScript
Intermediate · 3 min read
Stopwatches, video players, workout apps and trip trackers all show time the same way: 01:01:01 for one hour, one minute and one second. Under the hood they usually hold a single number of seconds, and turning that number into hh:mm:ss is a short piece of arithmetic.
In this tutorial you will write a function called hms that formats any number of seconds, including a full day, a hundred hours, a negative value and a fraction of a second. You'll also see why a popular one-line shortcut gets durations wrong. You need to know what a function is and how Math.floor rounds down.
Dividing and remainders
Two operators do all the work.
Math.floor(a / b) divides and throws away the fraction, so it tells you how many whole times b fits into a. The % operator gives you the remainder, what's left over after those whole times are taken out.
console.log(Math.floor(3661 / 3600)); // 1: one whole hour
console.log(3661 % 3600); // 61: seconds left over
There are 3,600 seconds in an hour and 60 in a minute. So the recipe is:
- Hours: how many whole 3,600s fit.
- Minutes: take what's left after the hours, and see how many whole 60s fit.
- Seconds: what's left after the minutes.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
113 Seconds to hh:mm:ss
fairFormat a number of seconds as hh:mm:ss — a journey of 3,661 seconds, a stopwatch at 59, a shift of a full day, and a duration of 100 hours. Handle a negative value and a fractional one.
Stuck? Three hints, smallest first
- 1. Hours are
Math.floor(total / 3600); minutes are the remainder divided by 60. - 2. Pad each part to two digits, and remember padding never truncates a three-digit hour.
- 3. The popular
new Date(ms).toISOString()one-liner cannot survive 24 hours.
Step 1: hours, minutes and seconds
const whole = 3661;
const h = Math.floor(whole / 3600);
const m = Math.floor((whole % 3600) / 60);
const s = whole % 60;
console.log(h, m, s); // 1 1 1
whole % 3600 is the 61 seconds left after the hours. Dividing that by 60 gives one whole minute. whole % 60 is the leftover second.
Step 2: pad each part to two digits
A clock shows 01, not 1. padStart(2, '0') adds a zero in front of anything shorter than two characters:
const pad = (n) => String(n).padStart(2, '0');
console.log([1, 1, 1].map(pad).join(':')); // 01:01:01
console.log([0, 0, 59].map(pad).join(':')); // 00:00:59
map(pad) pads each number, and join(':') puts colons between them.
Step 3: the shortcut that wraps at midnight
You may find this one-liner online. It builds a date from the seconds and cuts the time out of its text form:
const viaDate = (secs) => new Date(secs * 1000).toISOString().slice(11, 19);
console.log(viaDate(3661)); // 01:01:01
console.log(viaDate(86400)); // 00:00:00
It looks fine at 3,661 seconds. But 86,400 seconds is a full 24-hour day, and it shows 00:00:00. A date is a time of day, so it starts again at midnight. A duration has no midnight. A 24-hour shift should read 24:00:00.
Step 4: the function
function hms(totalSeconds) {
const sign = totalSeconds < 0 ? '-' : '';
const whole = Math.floor(Math.abs(totalSeconds));
const h = Math.floor(whole / 3600);
const m = Math.floor((whole % 3600) / 60);
const s = whole % 60;
const pad = (n) => String(n).padStart(2, '0');
return sign + [h, m, s].map(pad).join(':');
}
console.log(hms(3661)); // 01:01:01
console.log(hms(86400)); // 24:00:00
console.log(hms(360000)); // 100:00:00
Dividing never wraps, so 24 hours stays 24. And 100 hours prints as 100, because padStart only adds characters to short values. It never cuts a long one.
The first two lines handle the unusual inputs. They're explained in the next step.
Step 5: negatives and fractions
function hms(totalSeconds) {
const sign = totalSeconds < 0 ? '-' : '';
const whole = Math.floor(Math.abs(totalSeconds));
const h = Math.floor(whole / 3600);
const m = Math.floor((whole % 3600) / 60);
const s = whole % 60;
const pad = (n) => String(n).padStart(2, '0');
return sign + [h, m, s].map(pad).join(':');
}
console.log(hms(-90)); // -00:01:30
console.log(hms(59.9)); // 00:00:59
Math.abs removes the minus sign, the arithmetic runs on a positive number, and the sign is put back in front at the end. Why not just floor the negative number? Because Math.floor rounds down, and for negatives down means further from zero:
console.log(Math.floor(-90 / 3600)); // -1
That would be minus one hour plus some positive minutes, which is nonsense.
Math.floor on 59.9 gives 59. A stopwatch should never show a second that hasn't finished yet, so rounding down is right here.
Step 6: a short stopwatch form
Stopwatches often hide the hours until there are some. A regular expression can remove a leading 00::
function hms(totalSeconds) {
const sign = totalSeconds < 0 ? '-' : '';
const whole = Math.floor(Math.abs(totalSeconds));
const h = Math.floor(whole / 3600);
const m = Math.floor((whole % 3600) / 60);
const s = whole % 60;
const pad = (n) => String(n).padStart(2, '0');
return sign + [h, m, s].map(pad).join(':');
}
const short = (secs) => hms(secs).replace(/^00:/, '');
console.log(short(125)); // 02:05
/^00:/ means "00: at the very start". Only the hours can be there, so the minutes are never touched.
The full solution
The answer panel has hms, the short stopwatch form and the date shortcut side by side. The checks cover zero, a minute rolling over, a full day, the shortcut wrapping, a hundred hours, a fraction and a negative. Press Run to see the output.
function hms(totalSeconds) {
const sign = totalSeconds < 0 ? '-' : '';
const whole = Math.floor(Math.abs(totalSeconds));
const h = Math.floor(whole / 3600);
const m = Math.floor((whole % 3600) / 60);
const s = whole % 60;
const pad = (n) => String(n).padStart(2, '0');
return sign + [h, m, s].map(pad).join(':');
}
// A stopwatch usually drops the hours until there are some.
const short = (secs) => hms(secs).replace(/^00:/, '');
// The one-liner this replaces, and where it gives up.
const viaDate = (secs) => new Date(secs * 1000).toISOString().slice(11, 19);
console.log('3661 ->', hms(3661), ' 86400 ->', hms(86400), 'but via Date ->', viaDate(86400));
console.log('stopwatch:', short(125));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('zero', hms(0), '00:00:00');
test('the minute rolls over', hms(60), '00:01:00');
test('an hour, a minute and a second', hms(3661), '01:01:01');
test('a full day is 24 hours, not zero', hms(86400), '24:00:00');
test('which is where the Date one-liner wraps and lies', viaDate(86400), '00:00:00');
test('a hundred hours needs three digits, and padding never truncates', hms(360000), '100:00:00');
test('a fractional second floors rather than rounds up', hms(59.9), '00:00:59');
test('a negative duration keeps its sign outside the digits', hms(-90), '-00:01:30');
test('and a stopwatch can drop an empty hours field', short(125), '02:05');
Also exercise 1, which formatted a clock time from a Date; here the input is an elapsed duration, and that difference is the whole exercise. A duration has no midnight to wrap at, so the new Date(secs * 1000).toISOString().slice(11, 19) trick that circulates as the elegant answer reports a 24-hour shift as 00:00:00 and a 25-hour one as 01:00:00. Divide and take remainders instead; then 100 hours prints as 100:00:00, because padStart(2, '0') pads short values and leaves long ones alone (exercise 103).
Math.floor on the absolute value, with the sign put back in front, is what keeps -90 as -00:01:30; flooring a negative directly rounds towards minus infinity and gives -1 hours and positive minutes, which is nonsense (exercise 52 is the floor against trunc version of this). Flooring also means a stopwatch never shows a second it has not finished — 59.9 seconds is 00:00:59, and rounding up would let it display 01:00 before the minute exists.
Common mistakes
- Using the
Dateshortcut for durations. It starts again at 24 hours. - Flooring a negative number directly. Work on
Math.absand add the sign back. - Using
Math.roundon the seconds. 59.9 would become 60, and you'd print00:00:60.
Try it yourself
- Write the reverse:
toSeconds('01:01:01')should return 3661. (Hint:split(':')andNumber.) - Change
hmsto show days too, so 90,000 seconds is1d 01:00:00. - Format milliseconds:
hmsMs(3661250)should give01:01:01.250.