How to subtract date/time in JavaScript?

Ahmad Farid picture Ahmad Farid · Feb 9, 2011 · Viewed 338.7k times · Source

I have a field at a grid containing date/time and I need to know the difference between that and the current date/time. What could be the best way of doing so?

The dates are stored like "2011-02-07 15:13:06".

Answer

David Hedlund picture David Hedlund · Feb 9, 2011

This will give you the difference between two dates, in milliseconds

var diff = Math.abs(date1 - date2);

In your example, it'd be

var diff = Math.abs(new Date() - compareDate);

You need to make sure that compareDate is a valid Date object.

Something like this will probably work for you

var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));

i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.