mongodb - Getting difference in seconds from two dates in JavaScript - Stack Overflow

I have dates stored in MongoDB using Date(), MongoDB uses UTC it's date type, and as a string look

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.

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

I've tried this:

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());

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

It seems over plicated 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!

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.

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

I've tried this:

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());

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

It seems over plicated 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!

Share Improve this question asked Apr 3, 2012 at 15:08 dzmdzm 23.6k51 gold badges152 silver badges229 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

e.g.

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 will return only seonds, but not minutes, hours, etc.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745278523a4620167.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信