在Moment Js中获得两个日期之间的小时差

我可以使用MomentJs得到两个日期之间的差异,如下所示:

moment(end.diff(startTime)).format("m[m] s[s]")

但是,我还想在适用的情况下显示小时(仅当>= 60分钟已经过时)。

然而,当我试图检索持续时间小时使用以下:

var duration = moment.duration(end.diff(startTime));
var hours = duration.hours();

它返回当前的小时数,而不是两个日期之间的小时数。

我如何得到两个时刻之间的小时差?

637550 次浏览

你很接近了。你只需要使用duration.asHours()方法(参见的文档)。

var duration = moment.duration(end.diff(startTime));
var hours = duration.asHours();

下面的代码块展示了如何使用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)

或者你可以简单地做:

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

文档:在这里

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;
}
}};

你所需要做的就是将hours作为第二个参数传递给moments diff函数。

var a = moment([21,30,00], "HH:mm:ss")
var b = moment([09,30,00], "HH:mm:ss")
a.diff(b, 'hours') // 12

文档: https://momentjs.com/docs/#/displaying/difference/

例子:

const dateFormat = "YYYY-MM-DD HH:mm:ss";
// Get your start and end date/times
const rightNow = moment().format(dateFormat);
const thisTimeYesterday = moment().subtract(1, 'days').format(dateFormat);
// pass in hours as the second parameter to the diff function
const differenceInHours = moment(rightNow).diff(thisTimeYesterday, 'hours');


console.log(`${differenceInHours} hours have passed since this time yesterday`);
<script
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js">
</script>

 var start=moment(1541243900000);
var end=moment(1541243942882);
var duration = moment.duration(end.diff(startTime));
var hours = duration.asHours();

如您所见,开始日期和结束日期需要是此方法工作的时刻对象。

如果你想要两个日期之间的总分钟数,下面的代码将帮助你充分开始日期:2018-05-04 02:08:05结束日期:2018-05-14 09:04:07

function countDaysAndTimes(startDate,endDate){
return new Promise(function (resolve, reject) {
var dayObj = new Object;
var finalArray = new Array;


var datetime1 = moment(startDate);
var datetime2 = moment(endDate);
if(datetime1.format('D') != datetime2.format('D') || datetime1.format('M') != datetime2.format('M') ||  datetime1.format('YYYY') != datetime2.format('YYYY')){
var onlyDate1 = startDate.split(" ");
var onlyDate2 = endDate.split(" ");
var totalDays = moment(onlyDate2[0]).diff(moment(onlyDate1[0]), 'days')


// First Day Entry
dayObj.startDate = startDate;
dayObj.endDate = moment(onlyDate1[0]).add(1, 'day').format('YYYY-MM-DD')+" 00:00:00";
dayObj.minutes = moment(dayObj.endDate).diff(moment(dayObj.startDate), 'minutes');
finalArray.push(dayObj);


// Between Days Entry
var i = 1;
if(totalDays > 1){
for(i=1; i<totalDays; i++){
var dayObj1 = new Object;
dayObj1.startDate = moment(onlyDate1[0]).add(i, 'day').format('YYYY-MM-DD')+" 00:00:00";
dayObj1.endDate = moment(onlyDate1[0]).add(i+1, 'day').format('YYYY-MM-DD')+" 00:00:00";
dayObj1.minutes = moment(dayObj1.endDate).diff(moment(dayObj1.startDate), 'minutes');
finalArray.push(dayObj1);
}
}


// Last Day Entry
var dayObj2 = new Object;
dayObj2.startDate = moment(onlyDate1[0]).add(i, 'day').format('YYYY-MM-DD')+" 00:00:00";
dayObj2.endDate = endDate ;
dayObj2.minutes = moment(dayObj2.endDate).diff(moment(dayObj2.startDate), 'minutes');
finalArray.push(dayObj2);


}
else{
dayObj.startDate = startDate;
dayObj.endDate = endDate;
dayObj.minutes = datetime2.diff(datetime1, 'minutes');
finalArray.push(dayObj);
}
console.log(JSON.stringify(finalArray));
// console.table(finalArray);
resolve(finalArray);
});
}

输出

 [
{
"startDate":"2018-05-04 02:08:05",
"endDate":"2018-05-05 00:00:00",
"minutes":1311
},
{
"startDate":"2018-05-05 00:00:00",
"endDate":"2018-05-06 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-06 00:00:00",
"endDate":"2018-05-07 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-07 00:00:00",
"endDate":"2018-05-08 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-08 00:00:00",
"endDate":"2018-05-09 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-09 00:00:00",
"endDate":"2018-05-10 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-10 00:00:00",
"endDate":"2018-05-11 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-11 00:00:00",
"endDate":"2018-05-12 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-12 00:00:00",
"endDate":"2018-05-13 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-13 00:00:00",
"endDate":"2018-05-14 00:00:00",
"minutes":1440
},
{
"startDate":"2018-05-14 00:00:00",
"endDate":"2018-05-14 09:04:07",
"minutes":544
}
]

我知道这很老了,但这里有一个简单的解决方案:

const hourDiff = start.diff(end, "hours");

其中开始结束是力矩对象。

享受吧!

就我而言,我想要的是小时和分钟:

var duration = moment.duration(end.diff(startTime));
var hours = duration.hours(); //hours instead of asHours
var minutes = duration.minutes(); //minutes instead of asMinutes

有关更多信息,请参阅官方文档

有一个很棒的moment方法叫做fromNow(),它将以人类可读的形式返回特定时间的时间,就像这样:

moment('2019-04-30T07:30:53.000Z').fromNow() // an hour ago || a day ago || 10 days ago

或者如果你想在两个特定的日期之间,你可以使用:

var a = moment([2007, 0, 28]);
var b = moment([2007, 0, 29]);
a.from(b); // "a day ago"

摘自文档:

我知道这个问题已经回答了,但如果你想要一些递归的、更通用的、不依赖moment fromNow的东西,你可以使用我创建的这个函数。当然,您可以根据需要更改其逻辑,使其支持年和秒。

var createdAt = moment('2019-05-13T14:23:00.607Z');
var expiresAt = moment('2019-05-14T14:23:00.563Z');


// You can also add years in the beginning of the array or seconds in its end
const UNITS = ["months", "weeks", "days", "hours", "minutes"]
function getValidFor (createdAt, expiresAt, unit = 'months') {
const validForUnit = expiresAt.diff(createdAt, unit);
// you could adjust the if to your needs
if (validForUnit > 1 || unit === "minutes") {
return [validForUnit, unit];
}
return getValidFor(createdAt, expiresAt, UNITS[UNITS.indexOf(unit) + 1]);
}

根据Moment JS的新Deprecation警告enter image description here

你需要传递开始和结束日期格式的格式以及值,例如:

   let trackStartTime = "2020-12-29 09:59:19.07 +05:30";
let trackEndTime = "2020-12-29 11:04:19.07 +05:30" || moment().format("YYYY-MM-DD HH:mm:ss.SS Z");
let overallActivity = moment.duration(moment(trackEndTime, 'YYYY-MM-DD HH:mm:ss.SS Z').diff(moment(trackStartTime, 'YYYY-MM-DD HH:mm:ss.SS Z'))).asHours();

你只需要在moment.js中使用date.diff()方法

const now = moment.utc();
var end = moment("2021-09-13");
var days = now.diff(end, "days");
console.log(days)
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

也许对某人有用

          var ax = moment(
new Date().toLocaleString(), // today/now is 09/12/2021 10:00:00
"DD/MM/YYYY HH:mm:ss"
).diff(
moment(
"12/11/2022 13:43:11", // some time in future or past
"DD/MM/YYYY HH:mm:ss"
)
);
console.log('if today is in the future of the compared date then
result should be negative ==>', ax);
// ax bigger than 0 zero means date in past. ms less than zero is in future
 calcDifferential(from, to) {
const fromTime = this.$moment(from, 'hh:mm:ss')
const toTime = this.$moment(to, 'hh:mm:ss')
const ms = toTime.diff(fromTime)
const d = this.$moment.duration(ms)
const s = d.format()
return s
}

来源:https://momentjs.com/docs/#/displaying/difference/

let startDate = "2022-08-14";


let endDate = "2022-08-20";


let startDateMoment = moment(startDate.split('-')); // ["2022", "08", "14"]


let endDateMoment = moment(endDate.split('-'));


console.log('Difference: ', endDateMoment.diff(startDateMoment, 'hours')); // 6
<script src="https://momentjs.com/downloads/moment.js"></script>