Categories
JavaScript Answers

How to get the Month Name of Last Month using Moment.js?

Spread the love

To get the month name of last month using moment.js, we can use the subtract, startOf and format methods.

For instance, we can write:

const monthMinusOneName =  moment('2021-08-10').subtract(1, "month").startOf("month").format('MMMM');
console.log(monthMinusOneName)

We call moment to create moment date object.

Then we call subtract with 1 and 'month' to subtract 1 month from the moment date object.

Next, we call startOf with 'month' to return the moment date for the start of the subtracted date.

Finally, we call format with 'MMMM' to return the full month name.

Therefore, monthMinusOneName is 'July'.

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 *