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

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

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

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

谢谢!


当前回答

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

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

其他回答

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

如果你使用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 : "");
  }
}

我使用:

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

我在var str中得到"09:30"

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

我的特定用例的最佳场景是:

var duration = moment.duration("09:30"),
    formatted = moment.utc(duration.asMilliseconds()).format("HH:mm");

这改进了@Wilson的回答,因为它不访问私有内部属性_data。