Convert seconds to Days, Hours, Minutes, Seconds

Wed, 12 Dec 2018

Learn how to convert number of seconds into days, minutes, hours and seconds.

That's it. You can now create a countdown timer, display the difference between two dates or just print  the time until something great happens.

var seconds = 1001110 // 11 days 14:05:10

// compute the number of days
var days = Math.floor(seconds / (3600*24))
seconds -= days*3600*24

// compute the number of hours
var hours = Math.floor(seconds / 3600)
seconds -= hours*3600

// compute the number of minutes
var minutes = Math.floor(seconds / 60)
seconds -= minutes*60

You now have 4 variables with values as follows:

days === 11
hours === 14
minutes === 5
seconds === 10

Bonus! Learn how to pad the values with 0 so that they look pretty :D

function str_pad_left (string, pad, length) {
     return (new Array(length+1).join(pad)+string).slice(-length)
}

console.log(str_pad_left(minutes, '0', 2)) // "05"

Check this article to learn how to create a countdown timer.

Categories: how-to, javascript, nodejs, vuejs