简体   繁体   English

如何获得两个 Date.now() 之间的时差(以小时为单位)?

[英]How to get the time difference in hours between two Date.now()?

I have an object which updates often with time series stamps like:我有一个 object,它经常使用时间序列戳进行更新,例如:

obj = [{
  "value": 48.52062,
  "timestamp": 1652848223325
},
{
  "value": 43.33057,
  "timestamp": 1652838323281
},
{
  "value": 55.95403,
  "timestamp": 1652833823275
},
{
  "value": 51.71021,
  "timestamp": 1652830223280
},
{
  "value": 58.44382,
  "timestamp": 1652829323276
}]

How can I get the number of hours between these timestamps?我怎样才能得到这些时间戳之间的小时数? I am trying something like this:我正在尝试这样的事情:

 var timeStart = new Date(1652848686623).getHours(); var timeEnd = new Date(1652836523287).getHours(); var hourDiff = timeEnd - timeStart; console.log(hourDiff)
But I am getting 21 as output which is wrong, it is just 3. 但是我得到的 21 是 output,这是错误的,它只是 3。

This is because the .getHours() method of a Date object simply returns the hour of the day that the object represents.这是因为Date object 的.getHours()方法仅返回 object 表示的一天中的小时。 It does not return the total number of hours since the epoch, and therefore you cannot simply subtract the two values to obtain a meaningful result.它不返回自纪元以来的总小时数,因此您不能简单地减去这两个值来获得有意义的结果。

You can achieve what you want with a simple subtraction and division:您可以通过简单的减法和除法实现您想要的:

const timeStart = new Date(1652836523287)
const timeEnd   = new Date(1652848686623)
const hourDiff  = (timeEnd - timeStart) / 1000 / 60 / 60

NOTE that I swapped the two timestamps since clearly 165284... is after 165283... .请注意,我交换了两个时间戳,因为显然165284...165283...之后。

You can not just use getHours() on Date, and substract with them, because the "hours" is time of day, not the "absolute" time.您不能只在 Date 上使用getHours()并减去它们,因为“小时”是一天中的时间,而不是“绝对”时间。

Instead, You can just substract the end timestamp with start timestamp in your case, then just divide it by 3600000 (or 1000 * 60 * 60 ) to convert it to hour.相反,您可以在您的情况下用开始时间戳减去结束时间戳,然后将它除以3600000 (或1000 * 60 * 60 )以将其转换为小时。

 function getHourDiff(start, end) { return Math.floor((end - start) / 3600000) } const timeStart = 1652836523287; const timeEnd = 1652848686623 console.log(getHourDiff(timeStart, timeEnd));

 const timeStart = new Date(1652836523287) const timeEnd = new Date(1652848686623) const hourDiff = Math.abs(timeEnd - timeStart) / 36e5 console.log(hourDiff)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM