Convert seconds to hours minutes and seconds - Node.js Date

Node.js examples for Date:Second

Description

Convert seconds to hours minutes and seconds

Demo Code

/* http://codeaid.net/javascript/convert-seconds-to-hours-minutes-and-seconds-%28javascript%29 */
function secondsToTime(secs){
    var hours = Math.floor(secs / (60 * 60));

    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);
 
    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);
   /*ww w.  j  av  a 2s .co m*/
    var obj = {
        "h": hours,
        "m": minutes,
        "s": seconds
    };

    return obj;
}

/* allows to use '0'.repeat(...) */
String.prototype.repeat = function(num){
    if ( num == 0 ){
  return '';
    }
    return new Array( num + 1 ).join( this );
}

/* pads intergers with leading zeros */
function pad(x, width){
    s = x.toString();
    width -= s.length;
    return '0'.repeat(width) + s;
}

function format_time(x){
    var t = secondsToTime(x);
    return pad(t['h'], 2) + ':' + pad(t['m'], 2) + ':' + pad(t['s'],2);
}

Related Tutorials