JavaScript: How to add and subtract days from ISO date-time strings

For an explanation of what an ISO date-time string is, see this previous article:

JavaScript: How to create a formatted date time string

Now let’s say we get today’s date and we want to also get dates for one week ago and one week in the future. We can get today’s date in the form of an ISO date-time string like this:

let todaysDate = new Date().toISOString();

Here is the code (with comments) for creating a variable called ‘sevenDaysAgo’ that is set to today’s date minus seven days. It uses a temporary variable to transform today’s date with a combination of .setDate() and .getDate(), then places that transformed date into the sevenDaysAgo variable. After that, the sevenDaysAgo variable is turned into a Date object and converted into an ISO date-time string.

// set up a temporary date object 'd'
let d = new Date();

// use a combination of setDate and getDate +- the number of days
// on the temporary date object, then asign it to our variable
let sevenDaysAgo = d.setDate(d.getDate() - 7);

// turn our date variable into a new date, and convert it to an ISO date-time string
sevenDaysAgo = new Date(sevenDaysAgo).toISOString();

// see the result in the console
console.log(sevenDaysAgo)

Here is the code (without comments) for how to create a sevenDaysFromNow date:

let d = new Date();
let sevenDaysFromNow = d.setDate(d.getDate() + 7);
sevenDaysFromNow = new Date(sevenDaysFromNow).toISOString();
console.log(sevenDaysFromNow)

 

For more information about the  .setDate() and .getDate() functions, see:
https://www.w3schools.com/jsref/jsref_setdate.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate
https://www.w3schools.com/jsref/jsref_getDate.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDate