从JavaScript中的两个日期获取差异秒数
问题描述:
我使用Date()存储在MongoDB中的日期,MongoDB使用UTC日期类型,并且字符串看起来像Mon, 02 Apr 2012 20:16:31 GMT
。从JavaScript中的两个日期获取差异秒数
我想知道在这段时间和当前时间(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
。
它似乎过于复杂了。也许在MongoDB中有更好的方法,或者在JavaScript中有一个正确的方法来做到这一点?
任何建议将是伟大的 - 谢谢你!
答
您可以使用Date对象上的getTime()以毫秒为单位获得差值,然后将差值除以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);
答
(end_date.getTime() - current_date.getTime())/1000
getSeconds
将只返回seonds,但不分钟,小时等