Format seconds to an interval like '1d 7h 5s' - Node.js Date

Node.js examples for Date:Date Format

Description

Format seconds to an interval like '1d 7h 5s'

Demo Code


// ======================================================================
// format seconds to an interval like '1d 7h 5s'

String.prototype.formatSeconds = function () {
    var sec_num = parseInt(this, 10);
    var days    = Math.floor(sec_num / 86400);
    var hours   = Math.floor((sec_num - (days * 86400)) / 3600);
    var minutes = Math.floor((sec_num - (days * 86400  + hours * 3600)) / 60);
    var seconds = sec_num - (days * 86400) - (hours * 3600) - (minutes * 60);

    var time= '';
    if(days > 0) time+= days + 'd ';
    time += hours + 'h ' + minutes + 'm ' + seconds + ' s';
    return time;/*from  ww w.  j a v a2  s .c  o  m*/
}

// ======================================================================

Related Tutorials