Categories
JavaScript Answers

How to get 30 days prior to current date with JavaScript?

Spread the love

Sometimes, we want to get 30 days prior to current date with JavaScript.

In this article, we’ll look at how to get 30 days prior to current date with JavaScript.

How to get 30 days prior to current date with JavaScript?

To get 30 days prior to current date with JavaScript, we can use the setDate and getDate methods.

For instance, we write

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

console.log(today);
console.log(priorDate);

to get the day of the month of today‘s date with getDate.

Then we subtract 30 from it and use the difference as the argument for setDate.

Then we copy the new date value by passing the returned Date object to the Date constructor.

Conclusion

To get 30 days prior to current date with JavaScript, we can use the setDate and getDate methods.

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 *