从JavaScript中的两个日期开始以秒为单位的差异 [英] Getting difference in seconds from two dates in JavaScript

查看:49
本文介绍了从JavaScript中的两个日期开始以秒为单位的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Date()将日期存储在MongoDB中,MongoDB使用UTC作为日期类型,并且字符串类似于Mon, 02 Apr 2012 20:16:31 GMT.

I have dates stored in MongoDB using Date(), MongoDB uses UTC it's date type, and as a string looks like Mon, 02 Apr 2012 20:16:31 GMT.

我想了解此时间与当前时间之间的时间差(以秒为单位)(以UTC为单位).

I want to get the difference in time, in total seconds, between this time and the current time (in UTC).

我已经尝试过:

now = new Date();
current_date = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
end_date = obj.end_date (Mon, 02 Apr 2012 20:16:35 GMT);
d = new Date(end_date - current_date);
console.log(d.getSeconds());

这将显示22几秒钟,这显然是不正确的.

This is displaying 22 for seconds, which obviously isn't right.

似乎也太复杂了.也许在MongoDB中有更好的方法,或者在JavaScript中有正确的方法可以做到这一点?

It seems over complicated too. Maybe there's a better way within MongoDB or a correct way within JavaScript to do this?

任何建议都会很棒-谢谢!

Any suggestions would be great - thank you!

推荐答案

您可以在Date对象上使用getTime()来获取以毫秒为单位的差异,然后将差异除以1000;

You could use getTime() on the Date objects to get the difference in milliseconds then divide the difference by 1000;

例如

now = new Date();
current_date = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
end_date = obj.end_date (Mon, 02 Apr 2012 20:16:35 GMT);
var millisDiff = end_date.getTime() -  current_date.getTime();
console.log(millisDiff / 1000);

这篇关于从JavaScript中的两个日期开始以秒为单位的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆