I’m looking for a simple way to take a plain JavaScript Date
(like today) and go back X number of days.
For example, how would I calculate the date 5 days before today using a javascript subtract days from date
approach?
I’m looking for a simple way to take a plain JavaScript Date
(like today) and go back X number of days.
For example, how would I calculate the date 5 days before today using a javascript subtract days from date
approach?
You can use setDate() Method which is quick and easy
const today = new Date();
today.setDate(today.getDate() - 5); // Subtract 5 days
console.log(today);
Why I like this: This is the most straightforward way—no need for any external libraries, and it works well with native Date objects.
If you’re already using Moment.js
const moment = require('moment');
const fiveDaysAgo = moment().subtract(5, 'days');
console.log(fiveDaysAgo.format());
I had an ongoing project with moment.js where time calculations were frequent. It made date manipulation super smooth!
You can also use the Date constructor, which automatically handles date wrapping when adding or subtracting days.
const today = new Date();
const fiveDaysAgo = new Date(today.setDate(today.getDate() - 5)); // Subtract 5 days
console.log(fiveDaysAgo);
This approach returns a new Date object, so you won’t modify the original today variable.