Categories
JavaScript Answers

How to Get the Date That is 30 Days Prior to the Current Date with JavaScript?

Spread the love

To get the date that is 30 days prior to the current date with JavaScript, we can call the setDate method with the current date subtracted by 30 to get the date 30 days before the current date.

For instance, we can write:

const today = new Date()  
const priorDate = new Date().setDate(today.getDate() - 30)  
console.log(priorDate)

We create today’s date with the Date constructor with no arguments.

Then we call setDate with getDate to get the current date and minus that by 30 to get the date 30 days before today .

Get the Date That is 30 Days Prior to the Current Date with Moment.js

We can also use the subtract or add methods that come with moment.js to get the date that’s 30 days before today.

For example, we can write:

const priorDate = moment().subtract(30, 'days');  
console.log(priorDate)  
const priorDate2 = moment().add(-30, 'days');  
console.log(priorDate2)

to compute the date that’s 30 days before today with the subtract or add methods.

The first argument is the number of days to add or subtract.

The 2nd argument is the unit.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *