Subtract days from a date in JavaScript

jonhobbs picture jonhobbs · Aug 18, 2009 · Viewed 670.6k times · Source

Does anybody know of an easy way of taking a date (e.g. Today) and going back X days?

So, for example, if I want to calculate the date 5 days before today.

Answer

Stephen Wrighton picture Stephen Wrighton · Aug 18, 2009

Try something like this:

 var d = new Date();
 d.setDate(d.getDate()-5);

Note that this modifies the date object and returns the time value of the updated date.

var d = new Date();

document.write('Today is: ' + d.toLocaleString());

d.setDate(d.getDate() - 5);

document.write('<br>5 days ago was: ' + d.toLocaleString());