Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to format a duration in hours, minutes and seconds

Short answer

Divide with a remainder: 3600 seconds in an hour and 60 in a minute. padStart() adds a leading zero:

const formatDuration = (total) => {
  const hours = Math.floor(total / 3600);
  const minutes = Math.floor((total % 3600) / 60);
  const seconds = total % 60;
  const pad = (n) => String(n).padStart(2, '0');
  return `${hours}:${pad(minutes)}:${pad(seconds)}`;
};
 
console.log(formatDuration(3909));
console.log(formatDuration(59));

Output:

1:05:09
0:00:59

In words

For a text form, skip the parts that are zero:

const humanize = (minutes) => {
  const h = Math.floor(minutes / 60);
  const m = minutes % 60;
  return [h && `${h} h`, m && `${m} min`].filter(Boolean).join(' ') || '0 min';
};
 
console.log(humanize(135));
console.log(humanize(45));
console.log(humanize(120));

Output:

2 h 15 min
45 min
2 h

Minutes and seconds of a video

For a player, minutes and seconds are enough:

const seconds = 254;
 
console.log(`${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`);

Output:

4:14

Common mistake

Building the duration through a Date object breaks for durations longer than 24 hours and depends on the time zone. Division is simpler and more reliable:

const seconds = 90000;
 
console.log(new Date(seconds * 1000).toISOString().slice(11, 19));

Output:

01:00:00

90000 seconds is 25 hours, but the date shows only one hour.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.