是否有任何方法我可以使用moment.js格式方法持续时间对象?我在文档中找不到它,也没有看到它是持续时间对象的属性。
我希望能够做到以下几点:
var diff = moment(end).unix() - moment(start).unix();
moment.duration(diff).format('hh:mm:ss')
此外,如果有其他库可以轻松地容纳这种功能,我会很有兴趣推荐。
谢谢!
是否有任何方法我可以使用moment.js格式方法持续时间对象?我在文档中找不到它,也没有看到它是持续时间对象的属性。
我希望能够做到以下几点:
var diff = moment(end).unix() - moment(start).unix();
moment.duration(diff).format('hh:mm:ss')
此外,如果有其他库可以轻松地容纳这种功能,我会很有兴趣推荐。
谢谢!
当前回答
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.utc(totalMilliseconds).format("HH:mm:ss")
然而,任何超过24小时的时间都将重置为0。 但是分和秒是准确的。 所以我只用这部分来表示分和秒。
var minutesSeconds = moment.utc(totalMilliseconds).format("mm:ss")
现在我只需要总时间。
var hours = moment.duration(totalMilliseconds).asHours().toFixed()
为了得到我们都想要的格式,我们只需要把它们粘在一起。
var formatted = hours + ":" + minutesSeconds
如果totalMilliseconds是894600000,这将返回249:30:00。
希望这有帮助。请在评论中留下任何问题。;)
使用这个插件Moment Duration Format。
例子:
moment.duration(123, "minutes").format("h:mm");
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秒
根据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
使用moment-duration-format。
客户端框架(例如:React)
import moment from 'moment';
import momentDurationFormatSetup from 'moment-duration-format';
momentDurationFormatSetup(moment);
const breakLengthInMinutes = moment.duration(breakLengthInSeconds, 's').format('m');
服务器(node . js)
const moment = require("moment-timezone");
const momentDurationFormatSetup = require("moment-duration-format");
momentDurationFormatSetup(moment);
const breakLengthInMinutes = moment.duration(breakLengthInSeconds, 's').format('m');