How to perform date subtraction in javascript

A Date / Time object displays a time in a current situation (e.g. now() ). Displaying a difference of time is not part of a Date or Time object because the difference between e.g. May 1 and May 3 would result in, maybe, January 3, 1970, or maybe May 2, depends on how you start counting your delta on.

I would suggest putting your times into a timestamp which is a simple int in seconds. Do some substraction and voilá, there's your delta seconds. This delta can be used to apply to any other Object.


var atime = new Date("2010-12-05T08:03:22Z");
var btime = new Date("2010-01-11T08:01:57Z");

var delta_time = btime - atime; 

The value of delta_time will be the difference between the two dates in milliseconds.

If you're only interested in the difference, and don't care to differentiate between which is the later date, you might want to do

var delta_time = Math.abs(btime - atime);