Get First and Last Day of the previous Month in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 17, 2022

banner

Photo from Unsplash

Get First and Last Day of the previous Month in JavaScript #

Use the Date() constructor to get the first and last day of the previous month. The first 3 parameters the Date() constructor takes are the year, month and day of the month. The constructor returns a new Date object according to the supplied parameters.

index.js
const date = new Date('2022-03-17'); const firstDayPrevMonth = new Date(date.getFullYear(), date.getMonth() - 1, 1); // 👇️ Tue Feb 01 2022 00:00:00 console.log(firstDayPrevMonth); const lastDayPrevMonth = new Date(date.getFullYear(), date.getMonth(), 0); // 👇️ Mon Feb 28 2022 00:00:00 console.log(lastDayPrevMonth);

The 3 parameters we passed to the Date() constructor are:

  1. year - a 4-digit integer value representing the year of the date.
  2. monthIndex - an integer value from 0 (January) to 11 (December) that represents the month.
  3. day - an integer value representing the day of the month.

In the first example, we used the getFullYear method to get the year of the specified date.

We subtracted 1 from the result of the getMonth method to roll back into the previous month.

The Date object in JavaScript automatically handles the scenario where the year has to be adjusted, e.g. we are in January and we roll back to December of the previous year.

index.js
const date = new Date('2022-01-17'); const firstDayPrevMonth = new Date(date.getFullYear(), date.getMonth() - 1, 1); // 👇️ Wed Dec 01 2021 00:00:00 console.log(firstDayPrevMonth); const lastDayPrevMonth = new Date(date.getFullYear(), date.getMonth(), 0); // 👇️ Fri Dec 31 2021 00:00:00 console.log(lastDayPrevMonth);

In the examples above we got the first and last days of the previous month with a provided month of January.

The Date object automatically updated the year when we subtracted 1 from the index of the month of January.

To get the first day of the previous month, we supplied 1 as the day of the month for the 3rd parameter of the Date() constructor.

To get the last day of the previous month, we simply had to pass 0 as the day of the month.

The Date object automatically handles this by rolling back the month and setting the day of the month as the last day.

As the code snippet shows, the Date object also handles the scenario where the year has to be adjusted.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.