How to use format() on a moment.js duration?

前端 未结 28 2127
自闭症患者
自闭症患者 2020-11-27 04:34

Is there any way I can use the moment.js format method on duration objects? I can\'t find it anywhere in the docs and it doesn\'t seen to be an attribute on du

相关标签:
28条回答
  • 2020-11-27 05:11

    I use:

    var duration = moment.duration("09:30");
    var str = moment(duration._data).format("HH:mm");
    

    And I get "09:30" in var str.

    0 讨论(0)
  • 2020-11-27 05:12

    If all hours must be displayed (more than 24) and if '0' before hours is not necessary, then formatting can be done with a short line of code:

    Math.floor(duration.as('h')) + moment.utc(duration.as('ms')).format(':mm:ss')
    
    0 讨论(0)
  • 2020-11-27 05:12

    moment.duration(x).format() has been deprecated. You can usemoment.utc(4366589).format("HH:mm:ss") to get the desired response.

    console.log(moment.utc(4366589).format("HH:mm:ss"))
    <script src="https://momentjs.com/downloads/moment.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    0 讨论(0)
  • 2020-11-27 05:12
    import * as moment from 'moment'
    var sleep = require('sleep-promise');
    
    (async function () {
        var t1 = new Date().getTime();
        await sleep(1000); 
        var t2 = new Date().getTime();
        var dur = moment.duration(t2-t1); 
        console.log(`${dur.hours()}h:${dur.minutes()}m:${dur.seconds()}s`);
    })();
    
    
    0h:0m:1s
    
    0 讨论(0)
  • 2020-11-27 05:13

    convert duration to ms and then to moment:

    moment.utc(duration.as('milliseconds')).format('HH:mm:ss')
    
    0 讨论(0)
  • 2020-11-27 05:14

    To format moment duration to string

    var duration = moment.duration(86400000); //value in milliseconds
    var hours = duration.hours();
    var minutes = duration.minutes();
    var seconds = duration.seconds();
    var milliseconds = duration.milliseconds();
    
    var date = moment().hours(hours).minutes(minutes).seconds(seconds).millisecond(milliseconds);
    if (is12hr){
        return date.format("hh:mm:ss a");
    }else{
        return date.format("HH:mm:ss");
    }
    
    0 讨论(0)
提交回复
热议问题