如何在两个date.now()之间获得时间差异?
我有一个经常更新时间序列邮票的对象,例如:
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
}]
如何获得这些时间戳之间的小时数?我正在尝试这样的事情:
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.I have an object which updates often with time series stamps like:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为
.gethours()
date
对象的方法只是返回对象所代表的一天的时间。它不会返回自时代以来的总小时数,因此您不能简单地减去两个值以获得有意义的结果。您可以通过简单的减法和除法来实现想要的目标:
请注意,我换了两个时间戳,因为
165284 ...
是165283 ... 是。 /代码>。
This is because the
.getHours()
method of aDate
object simply returns the hour of the day that the object represents. 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:
NOTE that I swapped the two timestamps since clearly
165284...
is after165283...
.您不能仅在日期使用
gethours()
,而是与它们进行提取,因为“小时”是一天中的时间,而不是“绝对”时间。取而代之的是,您只需在情况下使用start Timestamp提取结束时间戳,然后将其除以
3600000
(或1000 * 60 * 60 * 60
)即可将其转换为小时。You can not just use
getHours()
on Date, and substract with them, because the "hours" is time of day, not the "absolute" time.Instead, You can just substract the end timestamp with start timestamp in your case, then just divide it by
3600000
(or1000 * 60 * 60
) to convert it to hour.