是否有任何方法我可以使用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')
此外,如果有其他库可以轻松地容纳这种功能,我会很有兴趣推荐。
谢谢!
当前回答
你不需要.format。像这样使用持续时间:
const duration = moment.duration(83, 'seconds');
console.log(duration.minutes() + ':' +duration.seconds());
// output: 1:23
我在这里找到了这个解决方案:https://github.com/moment/moment/issues/463
编辑:
用秒、分和小时填充:
const withPadding = (duration) => {
if (duration.asDays() > 0) {
return 'at least one day';
} else {
return [
('0' + duration.hours()).slice(-2),
('0' + duration.minutes()).slice(-2),
('0' + duration.seconds()).slice(-2),
].join(':')
}
}
withPadding(moment.duration(83, 'seconds'))
// 00:01:23
withPadding(moment.duration(6048000, 'seconds'))
// at least one day
其他回答
你可以使用numeric .js来格式化你的时长:
numeral(your_duration.asSeconds()).format('00:00:00') // result: hh:mm:ss
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秒
只需moment.js,不需要任何其他插件
moment().startOf('day').seconds(duration).format('HH:mm:ss')
// 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
如果必须显示所有的小时(超过24小时),如果小时之前的'0'是不必要的,那么格式化可以用一小行代码完成:
Math.floor(duration.as('h')) + moment.utc(duration.as('ms')).format(':mm:ss')