How to convert seconds to minutes and hours in javascript

I think you would find this solution very helpful.

You modify the display format to fit your needs with something like this -

function secondsToHms(d) {
    d = Number(d);
    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
    var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
    var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
    return hDisplay + mDisplay + sDisplay; 
}

The builtin JavaScript Date object can simplify the required code

 toTime(seconds) {
       var date = new Date(null);
       date.setSeconds(seconds);
       return date.toISOString().substr(11, 8);
    }

Tags:

Javascript