How to Subtract 30 Days From the Current Date in JavaScript

Last updated on September 29, 2022
How to Subtract 30 Days From the Current Date in JavaScript

1. Date setDate() and getDate() methods

To subtract 30 days from the current date in JavaScript:

  1. Use the Date() constructor to create a new Date object with the current date.
  2. Call the getDate() method on this object to get the days.
  3. Subtract 30 from the return value of getDate().
  4. Pass the result of the subtraction to the setDate() method.
// Current date: September 29, 2022
const date = new Date();

date.setDate(date.getDate() - 30);

// New date: August 30, 2022
console.log(date);

The Date getDate() method returns a number between 1 and 31 that represents the day of the month of the particular Date.

The Date setDate() method changes the day of the month of the Date object to the number passed as an argument.

If the days you specify would change the month or year of the Date, setDate() automatically updates the Date information to reflect this.

// April 25, 2022
const date = new Date('2022-04-25T00:00:00.000Z');

date.setDate(40);

// May 10, 2022
console.log(date); // 2022-05-10T00:00:00.000Z

console.log(date.getDate()); // 10

April has only 30 days, so passing 40 to setDate() here increments the month by one and sets the day of the month to 10.

2. date-fns subDays() function

Alternatively, we can use the subDays() function from the date-fns NPM package to subtract 30 days from the current date. subDays() takes a Date object and the number of days to subtract as arguments. It returns a new Date object with the days subtracted.

import { subDays } from 'date-fns';

// Current date: September 29, 2022
const date = new Date();

const newDate = subDays(date, 30);

// New date: August 30, 2022
console.log(newDate);

Note that subDays() returns a new Date object without mutating the one passed to it.

Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also