是否有任何方法我可以使用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')
此外,如果有其他库可以轻松地容纳这种功能,我会很有兴趣推荐。
谢谢!
当前回答
我的解决方案不涉及任何其他库,它与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))
其他回答
我使用:
var duration = moment.duration("09:30");
var str = moment(duration._data).format("HH:mm");
我在var str中得到"09:30"
使用这行代码:
moment.utc(moment.duration(4500, "seconds").asMilliseconds()).format("HH:mm:ss")
如果diff是一瞬间
var diff = moment(20111031) - moment(20111010);
var formated1 = moment(diff).format("hh:mm:ss");
console.log("format 1: "+formated1);
如果你使用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 : "");
}
}
原生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;
}