Skip to content Skip to sidebar Skip to footer

Getting Difference In Seconds From Two Dates In Javascript

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 tot

Solution 1:

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

e.g.

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

Solution 2:

(end_date.getTime() - current_date.getTime()) / 1000

getSeconds will return only seonds, but not minutes, hours, etc.

Post a Comment for "Getting Difference In Seconds From Two Dates In Javascript"