HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to subtract days from a plain Date?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
dayshowfromdatesubtractplain

Problem

Is there an easy way of taking a olain JavaScript Date (e.g. today) and going back X days?

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

Solution

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('
5 days ago was: ' + d.toLocaleString());

Code Snippets

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

Context

Stack Overflow Q#1296358, score: 1503

Revisions (0)

No revisions yet.