是否有任何方法我可以使用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')
此外,如果有其他库可以轻松地容纳这种功能,我会很有兴趣推荐。
谢谢!
当前回答
原生javascript怎么样?
var formatTime = function(integer) {
if(integer < 10) {
return "0" + integer;
} else {
return integer;
}
}
function getDuration(ms) {
var s1 = Math.floor(ms/1000);
var s2 = s1%60;
var m1 = Math.floor(s1/60);
var m2 = m1%60;
var h1 = Math.floor(m1/60);
var string = formatTime(h1) +":" + formatTime(m2) + ":" + formatTime(s2);
return string;
}
其他回答
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秒
我的解决方案不涉及任何其他库,它与diff > 24小时工作
var momentInSeconds = moment.duration(n,'seconds')
console.log(("0" + Math.floor(momentInSeconds.asHours())).slice(-2) + ':' + ("0" + momentInSeconds.minutes()).slice(-2) + ':' + ("0" + momentInSeconds.seconds()).slice(-2))
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.js中为持续时间添加某种格式。参见https://github.com/timrwood/moment/issues/463
其他几个可能会有所帮助的库是http://countdownjs.org/和https://github.com/icambron/twix.js
如果diff是一瞬间
var diff = moment(20111031) - moment(20111010);
var formated1 = moment(diff).format("hh:mm:ss");
console.log("format 1: "+formated1);