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

前端 未结 2 1603
别那么骄傲
别那么骄傲 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;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
    <div id="output" />

    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 })
    
    0 讨论(0)
  • 2021-01-20 16:03

    Maybe you can try this?

    moment(duration).format("DD MMM YYYY hh:mm: a")

    Though you might have to convert your seconds to milliseconds. This can be done by saying duration * 1000.

    Found from this answer: Moment js convert milliseconds into date and time

    0 讨论(0)
提交回复
热议问题