Subtracting dates in Javascript

30 Apr 2007 17:04

Here’s how to find the time 30 minutes ago:

var THIRTY_MINUTES_IN_MS = 30 * 60 * 1000;

var now = new Date();
var nowMs = now.getTime();

var thenMs = nowMs - THIRTY_MINUTES_IN_MS;
var then = new Date(thenMs);

The secret is that Date.getTime returns the number of milliseconds since the epoch, and that the Date constructor accepts these millisecond values.