Convert milliseconds to time - Node.js Date

Node.js examples for Date:Millisecond

Description

Convert milliseconds to time

Demo Code

function msToTime(ms) {
    if (ms === undefined || ms === 0) { return '0' }
    var decimals = 0
    var unit = ''
    var amount = 0
    if (ms < 1000 * 60) {
        decimals = 1//  w w  w  . j  a v a  2 s  . com
        unit = 'sec'
        amount = ms / 1000
    } else if (ms < 1000 * 60 * 60) {
        decimals = 1
        unit = 'min'
        amount = ms / 1000 / 60
    } else if (ms < 1000 * 60 * 60 * 24) {
        decimals = 1
        unit = 'h'
        amount = ms / 1000 / 60 / 60
    } else if (ms < 1000 * 60 * 60 * 24 * 7) {
        decimals = 2
        unit = 'd'
        amount = ms / 1000 / 60 / 60 / 24
    } else {
        decimals = 2
        unit = 'w'
        amount = ms / 1000 / 60 / 60 / 24 / 7
    }
    return amount.toFixed(decimals) + ' ' + unit
}

Related Tutorials