How to Get Last Month Name using Moment.js and JavaScript?

In this article, we are going to learn how to get the last month name using Moment.js and Javascript. You may be wondering what Moment.js is used for.

MomentJS is a library of JavaScript that helps in parsing, validating, displaying date/time and manipulating in JavaScript in a simple way. This library allows users to display dates as per localisation and in readable format.

Now the question arises, Is MomentJS still needed? There’s no particular answer. MomentJS is used widely for date and time formatting. MomentJS makes a developers life easier by saving a lot of time by providing pre-built functions to play with the dates as per client’s requirement.

In this tutorial, we will show you how to get Month name from the date. To get the month name of last month using Moment.js, we will use the subtract, startOf and format methods.

Code to Get Previous Month Name in JavaScript

<!DOCTYPE html>
<html>
  <head>
    <title>Using Moment.js Is Easy | CodingIsEasy.com</title>
  </head>
  <body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

    <script>
      const monthMinusOneName = moment().subtract(1, "month").startOf("month").format('MMMM');
      alert(monthMinusOneName);
    </script>

  </body>
</html>

Moment() is called to create moment date object. Subtract is then called with 1 and ‘month has to subtact 1 month from the object that we created above. Then we call startof with ‘month to return the moment date of the subtracted date. At the end we call, format to get the month name.

That’s it for the blog. Hope you have learnt to use MomentJS. Comment down in case you get stuck anywhere.

Leave a Comment