How do I subtract one week from this date in JavaScript?


You need to subtract one week i.e. 7 days from the current date. Following is the syntax −

var anyVariableName=new Date(yourCurrentDate.setDate(yourCurrentDate.getDate() - 7)

At first, get the current date −

var currentDate = new Date();
console.log("The current Date="+currentDate);

Now, set the new date with setDate() method and subtract 7 days −

Example

var currentDate = new Date();
console.log("The current Date="+currentDate);
var before7Daysdate=new Date(currentDate.setDate(currentDate.getDate() - 7));
console.log("The One week ago date="+before7Daysdate);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo60.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo60.js
The current Date=Tue Jul 14 2020 19:12:43 GMT+0530 (India Standard Time)
The One week ago date=Tue Jul 07 2020 19:12:43 GMT+0530 (India Standard Time)

Updated on: 03-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements