如何获得两个日期对象之间的小时差异? [重复]

时间:2021-09-06 21:30:49

This question already has an answer here:

这个问题在这里已有答案:

I got two Date objects and I want to calculate the difference in hours.

我有两个Date对象,我想计算小时数的差异。

If the difference in hours is less than 18 hours, I want to push the date object into an array.

如果小时差异小于18小时,我想将日期对象推送到数组中。

Javascript / jQuery, doesn't really matter; what works the best will do.

Javascript / jQuery,并不重要;什么是最好的将做。

3 个解决方案

#1


118  

The simplest way would be to directly subtract the date objects from one another.

最简单的方法是直接从彼此中减去日期对象。

For example:

例如:

var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds difference into hours.

减法返回两个日期之间的差异,以毫秒为单位。 36e5是60 * 60 * 1000的科学记数法,除以将毫秒差异转换为小时。

#2


23  

Try using getTime (mdn doc) :

尝试使用getTime(mdn doc):

var diff = Math.abs(date1.getTime() - date2.getTime()) / 3600000;
if (diff < 18) { /* do something */ }

Using Math.abs() we don't know which date is the smallest. This code is probably more relevant :

使用Math.abs()我们不知道哪个日期最小。这段代码可能更相关:

var diff = (date1 - date2) / 3600000;
if (diff < 18) { array.push(date1); }

#3


3  

Use the timestamp you get by calling valueOf on the date object:

使用在日期对象上调用valueOf获得的时间戳:

var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours

#1


118  

The simplest way would be to directly subtract the date objects from one another.

最简单的方法是直接从彼此中减去日期对象。

For example:

例如:

var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds difference into hours.

减法返回两个日期之间的差异,以毫秒为单位。 36e5是60 * 60 * 1000的科学记数法,除以将毫秒差异转换为小时。

#2


23  

Try using getTime (mdn doc) :

尝试使用getTime(mdn doc):

var diff = Math.abs(date1.getTime() - date2.getTime()) / 3600000;
if (diff < 18) { /* do something */ }

Using Math.abs() we don't know which date is the smallest. This code is probably more relevant :

使用Math.abs()我们不知道哪个日期最小。这段代码可能更相关:

var diff = (date1 - date2) / 3600000;
if (diff < 18) { array.push(date1); }

#3


3  

Use the timestamp you get by calling valueOf on the date object:

使用在日期对象上调用valueOf获得的时间戳:

var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours