jQuery 如何获得两个日期对象之间的小时差?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19225414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the hours difference between two date objects?
提问by Anoniem Anoniem
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,并不重要;什么效果最好。
回答by Boaz - Reinstate Monica
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
,除以将毫秒差转换为小时。
回答by leaf
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); }
回答by Matt Zeunert
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