1. Date setDate() and getDate() methods
To subtract 30 days from the current date in JavaScript:
- Use the
Date()
constructor to create a newDate
object with the current date. - Call the
getDate()
method on this object to get the days. - Subtract 30 from the return value of
getDate()
. - 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.
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.