JavaScript Date: One week ago.

This is a short tutorial on how to create a JavaScript date that is “7 days ago”. Depending on your needs, you can adjust this script to be “one month ago” or “one year ago”. For this tutorial, I am going to use standard JavaScript instead of relying on an external library (in many of the Stack Overflow answers that I saw, people were recommending external libraries, which I found to be a tad bit frustrating).

The code:

//Get today's date using the JavaScript Date object.
var ourDate = new Date();

//Change it so that it is 7 days in the past.
var pastDate = ourDate.getDate() - 7;

//Log the date to our web console.

In the example above we:

  1. Got the current date and time by using the JavaScript Date object.
  2. We deducted 7 days from the current date.
  3. We changed our original date to the “7 days ago” date by using the setDate method.
  4. We logged it to our web console for example purposes.

Note: If you want to get “30 days ago” instead of a week ago, then you can simply deduct 30 instead of 7. Hopefully, you found this short guide to be useful!