How to Subtract Days from a Date in JavaScript

To subtract days from a date in JavaScript, use the “getDate()” and “setDate()” methods or use “setTime()” and “getTime()” methods.

Method 1: Using the getDate() and setDate() methods

The “getDate()” method returns the current day of the month.

The “setDate()” method returns a new day value, subtracting the desired number of days.

Syntax

Date.setDate(numberOfDay);

Date.getDate();

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

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.

Method 2: Using the getTime() and setTime() methods

The setTime() method is used to set the date and time in milliseconds by subtracting or adding it from midnight, Jan 1, 1970.

The getTime() method returns a number that specifies the number of milliseconds from midnight, Jan 1, 1970, till the day we are subtracting or adding. It does not accept any kind of variable or parameter.

Syntax

Date.setTime(milliseconds);
Date.getTime();

Example

function subtractDaysFromDate(date, daysToSubtract) {
   const millisecondsPerDay = 24 * 60 * 60 * 1000;
   const newTime = date.getTime() - (daysToSubtract * millisecondsPerDay);
   date.setTime(newTime);
   return date;
}

// Example usage:
const currentDate = new Date();
console.log("Current Date:", currentDate);

const newDate = subtractDaysFromDate(new Date(currentDate), 5);
console.log("Date after subtracting 5 days:", newDate);

Output

Current Date: 2023-08-18T10:42:10.944Z
Date after subtracting 5 days: 2023-08-13T10:42:10.944Z

That’s it!