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

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

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

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

谢谢!


当前回答

简短版本(一行代码):

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 Duration Format。

例子:

moment.duration(123, "minutes").format("h:mm");

这可以用于将前两个字符作为小时,最后两个字符作为分钟。同样的逻辑也适用于秒。

/** * PT1H30M -> 0130 * @param {ISO String} isoString * @return {string} absolute 4 digit number HH:mm */ const parseIsoToAbsolute = (isoString) => { const durations = moment.duration(isoString).as('seconds'); const momentInSeconds = moment.duration(durations, 'seconds'); let hours = momentInSeconds.asHours().toString().length < 2 ? momentInSeconds.asHours().toString().padStart(2, '0') : momentInSeconds.asHours().toString(); if (!Number.isInteger(Number(hours))) hours = '0'+ Math.floor(hours); const minutes = momentInSeconds.minutes().toString().length < 2 ? momentInSeconds.minutes().toString().padEnd(2, '0') : momentInSeconds.minutes().toString(); const absolute = hours + minutes; return absolute; }; console.log(parseIsoToAbsolute('PT1H30M')); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

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

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 " > < /脚本>

const duration = moment.duration(62, 'hours');
const n = 24 * 60 * 60 * 1000;
const days = Math.floor(duration / n);
const str = moment.utc(duration % n).format('H [h] mm [min] ss [s]');
console.log(`${days > 0 ? `${days} ${days == 1 ? 'day' : 'days'} ` : ''}${str}`);

打印:

2天14小时00分00秒