Hi Friends 👋,

Welcome To Infinitbility! ❤️

To get the previous month in moment js, use the subtract(1, "month") method to subtract the month in date and use format('MMMM') to get the month name from subtracted date.

Just import moment in your file and call moment().subtract(1, "month").format('MMMM') and it will return previous month.

moment().subtract(1, "month").format('MMMM')

Today, I’m going to show How do I get the previous month using moment js, here I will use the momentjs standard method subtract() and format() to get last month.

Let’s start today’s tutorial How do you get the previous month using moment js?

Table of content

  1. Installation
  2. Example in reactjs

Installation

Use the below installation command as per your package manager, moment support npm, Yarn, NuGet, spm, and meteor.

npm install moment --save   # npm
yarn add moment             # Yarn
Install-Package Moment.js   # NuGet
spm install moment --save   # spm
meteor add momentjs:moment  # meteor

Example in reactjs

In the following example, we are going to do

  1. import the moment package
  2. example of current date time to get last month
  3. example of custom date time to get last month

let’s write the code.

import moment from "moment";

function App() {
  return (
    <div>
        {/* example of current date time to get last month */}
        {console.log(moment().subtract(1, "month").format('MMMM'))}
        {console.log("----")}
        {/* example of custom date time to get last month */}
        {console.log(moment('2016-10-08 10:29:23').subtract(1, "month").format('MMMM'))}
    </div>
  );
}

export default App;

In the above program, we call subtract() and format() to get a previous month of the current date or custom date.

let’s check the output.

MomentJs, Example of get last month of the date
MomentJs, Example of get last month of the date

I hope it’s help you, All the best 👍.