Sometimes, we want to get the month name of last month using Moment.js and JavaScript.
In this article, we’ll look at how to get the month name of last month using Moment.js and JavaScript.
How to get the month name of last month using Moment.js and JavaScript?
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'.
Conclusion
To get the month name of last month using Moment.js and JavaScript., we can use the subtract, startOf and format methods.