Using moment.js how do I give a specific format for a duration

前端 未结 2 1605
别那么骄傲
别那么骄傲 2021-01-20 15:21

Given a duration of a number of seconds coming from an API as duration_seconds = 86485.

(1 day, 0 hours, 1 minute, 1 second)

I was going to use

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-20 16:02

    The moment-duration-format plugin can assist you with this.

    // your input
    var duration_seconds = 86485;
    
    // create a moment-duration object
    var duration = moment.duration(duration_seconds, 'seconds');
    
    // format the object with a string
    var formatted = duration.format('h[h] m[m] s[s]');
    
    // displaying the output here
    document.getElementById('output').innerHTML = formatted;
    
    
    

    Note that by default it will omit units that are not relevant, so if your input is 3, it's just going to say "3s", not "0h 0m 3s".

    If you want to change this behavior, set trim:false, per the documentation. For example, to get the format you mentioned in comments, use:

    .format('hh:mm:ss', { trim: false })
    

提交回复
热议问题