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

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

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

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

谢谢!


当前回答

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

/** * 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>

其他回答

只需moment.js,不需要任何其他插件

moment().startOf('day').seconds(duration).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")
}

示例案例:

如果你使用Angular >2,我做了一个受@hai-alaluf answer启发的Pipe。

import {Pipe, PipeTransform} from "@angular/core";

@Pipe({
  name: "duration",
})

export class DurationPipe implements PipeTransform {

  public transform(value: any, args?: any): any {

    // secs to ms
    value = value * 1000;
    const days = Math.floor(value / 86400000);
    value = value % 86400000;
    const hours = Math.floor(value / 3600000);
    value = value % 3600000;
    const minutes = Math.floor(value / 60000);
    value = value % 60000;
    const seconds = Math.floor(value / 1000);
    return (days ? days + " days " : "") +
      (hours ? hours + " hours " : "") +
      (minutes ? minutes + " minutes " : "") +
      (seconds ? seconds + " seconds " : "") +
      (!days && !hours && !minutes && !seconds ? 0 : "");
  }
}
// set up
let start = moment("2018-05-16 12:00:00"); // some random moment in time (in ms)
let end = moment("2018-05-16 12:22:00"); // some random moment after start (in ms)
let diff = end.diff(start);

// execution
let f = moment.utc(diff.asMilliseconds()).format("HH:mm:ss.SSS");
alert(f);

看看JSFiddle

使用这行代码:

moment.utc(moment.duration(4500, "seconds").asMilliseconds()).format("HH:mm:ss")