Convert milliseconds to hours and minutes using Momentjs

前端 未结 11 2476
滥情空心
滥情空心 2020-12-09 15:00

I am new to Momentjs. I am trying to use it to convert milliseconds to hours and minutes. Below, x is milliseconds

x = 433276000
var y = moment.duration(x, \         


        
11条回答
  •  旧时难觅i
    2020-12-09 15:15

    Here is a function that formats it for you into a string.

    function ms_to_str(val) {
    
        let tempTime = moment.duration(val),
            timeObj = {
                years: tempTime.years(),
                months: tempTime.months(),
                days: tempTime.days(),
                hrs: tempTime.hours(),
                mins: tempTime.minutes(),
                secs: tempTime.seconds(),
                ms: tempTime.milliseconds()
            },
    
            timeArr = [];
    
        for (let k in timeObj) {
            if (Number(timeObj[k]) > 0) {
                timeArr.push(`${timeObj[k]} ${k}`)
            }
        }
    
        return timeArr.join(', ');
    }
    

    Then simply call ms_to_str(2443253) which returns 40 mins, 43 secs, 253 ms.

    If you do not need to show milliseconds, simply comment off the ms: tempTime.milliseconds().toString().padStart(3, '0') line.

提交回复
热议问题