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

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

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

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

谢谢!


当前回答

根据ni-ko-o-kin的回答:

meassurements = ["years", "months", "weeks", "days", "hours", "minutes", "seconds"];
withPadding = (duration) => {
    var step = null;
    return meassurements.map((m) => duration[m]()).filter((n,i,a) => {
        var nonEmpty = Boolean(n);
        if (nonEmpty || step || i >= a.length - 2) {
            step = true;
        }
        return step;
    }).map((n) => ('0' + n).slice(-2)).join(':')
}

duration1 = moment.duration(1, 'seconds');
duration2 = moment.duration(7200, 'seconds');
duration3 = moment.duration(604800, 'seconds');

withPadding(duration1); // 00:01
withPadding(duration2); // 02:00:00
withPadding(duration3); // 01:07:00:00:00

其他回答

如果diff是一瞬间

var diff = moment(20111031) - moment(20111010);
var formated1 = moment(diff).format("hh:mm:ss");
console.log("format 1: "+formated1);
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

简短版本(一行代码):

moment.duration(durationInMs).asHours()|0||"00" + ":" + moment.utc(durationInMs).format("mm:ss")

扩展的版本:

export const formatDuration = (durationInMs) => {
    const hours = Math.floor(moment.duration(durationInMs).asHours()) || "00"
    return hours + ":" + moment.utc(durationInMs).format("mm:ss")
}

示例案例:

我们正在考虑在moment.js中为持续时间添加某种格式。参见https://github.com/timrwood/moment/issues/463

其他几个可能会有所帮助的库是http://countdownjs.org/和https://github.com/icambron/twix.js

这对我来说很管用:

moment({minutes: 150}).format('HH:mm') // 01:30