本文翻译自:Get hours difference between two dates in Moment Js
I'm able to get the difference between two dates using MomentJs as follows: 我可以使用MomentJs获得两个日期之间的差异,如下所示:
moment(end.diff(startTime)).format("m[m] s[s]")
However, I also want to display the hour when applicable (only when >= 60 minutes have passed). 但是,我也希望在适用时显示小时(仅当> = 60分钟时才显示)。
However, when I try to retrieve the duration hours using the following: 但是,当我尝试使用以下内容检索持续时间时:
var duration = moment.duration(end.diff(startTime));
var hours = duration.hours();
it is returning the current hour and not the number of hours between the two dates. 它返回当前小时而不是两个日期之间的小时数。
How do I get the difference in hours between two Moments? 如何获得两个时刻之间的小时差异?
参考:https://stackoom.com/question/1hWoM/获取Moment-Js中两个日期之间的小时差异
You were close. 你很亲密 You just need to use the duration.asHours()
method (see the docs ). 您只需要使用duration.asHours()
方法(请参阅文档 )。
var duration = moment.duration(end.diff(startTime));
var hours = duration.asHours();
Following code block shows how to calculate the difference in number of days between two dates using MomentJS. 以下代码块显示了如何使用MomentJS计算两个日期之间的天数差异。
var now = moment(new Date()); //todays date
var end = moment("2015-12-1"); // another date
var duration = moment.duration(now.diff(end));
var days = duration.asDays();
console.log(days)
Or you can do simply: 或者你可以做到:
var a = moment('2016-06-06T21:03:55');//now
var b = moment('2016-05-06T20:03:55');
console.log(a.diff(b, 'minutes')) // 44700
console.log(a.diff(b, 'hours')) // 745
console.log(a.diff(b, 'days')) // 31
console.log(a.diff(b, 'weeks')) // 4
docs: here docs: 这里
var __startTime = moment("2016-06-06T09:00").format();
var __endTime = moment("2016-06-06T21:00").format();
var __duration = moment.duration(moment(__endTime).diff(__startTime));
var __hours = __duration.asHours();
console.log(__hours);
var timecompare = {
tstr: "",
get: function (current_time, startTime, endTime) {
this.tstr = "";
var s = current_time.split(":"), t1 = tm1.split(":"), t2 = tm2.split(":"), t1s = Number(t1[0]), t1d = Number(t1[1]), t2s = Number(t2[0]), t2d = Number(t2[1]);
if (t1s < t2s) {
this.t(t1s, t2s);
}
if (t1s > t2s) {
this.t(t1s, 23);
this.t(0, t2s);
}
var saat_dk = Number(s[1]);
if (s[0] == tm1.substring(0, 2) && saat_dk >= t1d)
return true;
if (s[0] == tm2.substring(0, 2) && saat_dk <= t2d)
return true;
if (this.tstr.indexOf(s[0]) != 1 && this.tstr.indexOf(s[0]) != -1 && !(this.tstr.indexOf(s[0]) == this.tstr.length - 2))
return true;
return false;
},
t: function (ii, brk) {
for (var i = 0; i <= 23; i++) {
if (i < ii)
continue;
var s = (i < 10) ? "0" + i : i + "";
this.tstr += "," + s;
if (brk == i)
break;
}
}};