是否有任何方法我可以使用moment.js格式方法持续时间对象?我在文档中找不到它,也没有看到它是持续时间对象的属性。

我希望能够做到以下几点:

var diff = moment(end).unix() - moment(start).unix();
moment.duration(diff).format('hh:mm:ss')

此外,如果有其他库可以轻松地容纳这种功能,我会很有兴趣推荐。

谢谢!


当前回答

var diff = moment(end).unix() - moment(start).unix();
moment.utc(moment.duration(diff).asMilliseconds()).format("HH:mm:ss.SSS");

其他回答

如果必须显示所有的小时(超过24小时),如果小时之前的'0'是不必要的,那么格式化可以用一小行代码完成:

Math.floor(duration.as('h')) + moment.utc(duration.as('ms')).format(':mm:ss')

Moment.duration (x).format()已弃用。 您可以使用moment.utc(4366589).format("HH:mm:ss")来获得所需的响应。

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

如果diff是一瞬间

var diff = moment(20111031) - moment(20111010);
var formated1 = moment(diff).format("hh:mm:ss");
console.log("format 1: "+formated1);

我的解决方案不涉及任何其他库,它与diff > 24小时工作

var momentInSeconds = moment.duration(n,'seconds')
console.log(("0" + Math.floor(momentInSeconds.asHours())).slice(-2) + ':' + ("0" + momentInSeconds.minutes()).slice(-2) + ':' + ("0" + momentInSeconds.seconds()).slice(-2))
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