Search code examples
javascriptdateformatseconds

Convert seconds to HH-MM with JavaScript?


I have been using this excellent function for HH:MM:SS, but how could I modify it to return only HH:MM with either the seconds truncated or rounded.

function formatSeconds(seconds)
{
    var date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}

Solution

  • The problem with using a Date to format seconds is that it can't handle times longer than 24 hours and the vagaries of Dates. Simply reformat the value as required:

    function formatSeconds(seconds) {
      function z(n) {return (n < 10 ? '0' : '') + n;}
      return z(seconds / 3600 | 0) + ':' + z((seconds % 3600) / 60 | 0)
    }
    
    // Some examples
    [0,1,61,3600,3660,765467].forEach(function (seconds) {
      console.log(seconds + ' -> ' + formatSeconds(seconds))
    });

    No Date, no regular expression, no library, no dependencies and works in every host that ever supported ECMAScript.