Convert Seconds to Days, Hours, Minutes and Seconds in JS

avatar

Borislav Hadzhiev

Last updated: Jan 20, 2022

banner

Photo from Unsplash

Convert Seconds to Days, Hours, Minutes and Seconds in JS #

To convert seconds to days, hours, minutes and seconds, get the amount of full days and calculate the remainder of hours, minutes and seconds. Then, format the values according to your use case.

index.js
function toDaysMinutesSeconds(totalSeconds) { const seconds = Math.floor(totalSeconds % 60); const minutes = Math.floor((totalSeconds % 3600) / 60); const hours = Math.floor((totalSeconds % (3600 * 24)) / 3600); const days = Math.floor(totalSeconds / (3600 * 24)); const secondsStr = makeHumanReadable(seconds, 'second'); const minutesStr = makeHumanReadable(minutes, 'minute'); const hoursStr = makeHumanReadable(hours, 'hour'); const daysStr = makeHumanReadable(days, 'day'); return `${daysStr}${hoursStr}${minutesStr}${secondsStr}`.replace(/,\s*$/, ''); } function makeHumanReadable(num, singular) { return num > 0 ? num + (num === 1 ? ` ${singular}, ` : ` ${singular}s, `) : ''; } console.log(toDaysMinutesSeconds(565)); // 👉️ 9 minutes, 25 seconds console.log(toDaysMinutesSeconds(2073600)); // 👉️ 24 days console.log(toDaysMinutesSeconds(703800)); // 👉️ 8 days, 3 hours, 30 minutes

The toDaysMinutesSeconds function takes the number of seconds as a parameter and returns a string that contains the full number of days and the remainder of hours, minutes and seconds.

The Math.floor function, rounds a number down if the number has a decimal, otherwise it returns the number as is.

index.js
console.log(Math.floor(4.99)); // 👉️ 4 console.log(Math.floor(4.01)); // 👉️ 4 console.log(Math.floor(4)); // 👉️ 4
This ensures we don't get values with a decimal, e.g. 4.213 for the days. For example if the value for the days has a decimal, we want to hide the decimal and show the number of hours.

We used the modulo (%) operator to get the remainder of hours, minutes and seconds after we calculated the full days.

The makeHumanReadable function takes care of formatting the number as a human-readable string, e.g. 24 days, 5 hours, 30 minutes, 16 seconds.

In the examples, if the value is 0, we simply skip it and don't include it in the final string, however, you could change the makeHumanReadable function if you want to show 0 values as well.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.