To subtract days from a date in JavaScript, you can follow these steps:
- Create a new Date object for the given date.
- Use the “getDate()” method to get the current day of the month.
- Use the “setDate()” method to set a new day value, subtracting the desired number of days.
Example
const currentDate = new Date();
const daysToSubtract = 5;
// Get the current day of the month
const currentDay = currentDate.getDate();
// Subtract the desired number of days and set the new date
currentDate.setDate(currentDay - daysToSubtract);
console.log(currentDate);
Output
2023-04-17T19:55:33.688Z
In the above code, we created a new Date object called currentDate that represents the current date and time.
For this example, we want to subtract 5 days, so we set the daysToSubtract variable to 5.
In the next step, we used the “getDate()” method to get the current day of the month and the “setDate()” method to set a new day value by subtracting the desired number of days (daysToSubtract).
The currentDate variable now represents the date 5 days before the original date.
Remember that when you use the “setDate()” method with a negative value or less than 1, the Date object will automatically adjust the month and year as needed. This means this approach works correctly even when crossing month or year boundaries.

Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.