Get the First day of the Previous Month in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 25, 2022

banner

Photo from Unsplash

Get the First day of the Previous Month #

To get the first day of the previous month, use the Date() constructor to create a date object, passing it a call to the getFullYear() method for the year, a call to the getMonth() method - 1 to get the previous month and 1 for the day.

index.js
function getFirstDayPreviousMonth() { const date = new Date(); return new Date(date.getFullYear(), date.getMonth() - 1, 1); } console.log(getFirstDayPreviousMonth());

We passed the following 3 arguments to the Date() constructor:

  1. The year
  2. The month - notice that we subtracted 1 from the return value of the getMonth method to get the previous month.
  3. The day

We used the Date.getFullYear method to get the current year.

We used the Date.getMonth method to get the current month.

The getMonth method returns an integer from 0 (January) to 11 (December).

Months are zero-based in JavaScript and go from 0 (January) to 11 (December).

We hard-coded 1 for the day because we want the first day of the month.

To make your code more readable, you could extract the values for the previous month and the day in variables.

index.js
function getFirstDayPreviousMonth() { const date = new Date(); const prevMonth = date.getMonth() - 1; const firstDay = 1; return new Date(date.getFullYear(), prevMonth, firstDay); } console.log(getFirstDayPreviousMonth());

This function would also work if the previous month is December of last year.

index.js
// 👉️ Sun Dec 01 2024 console.log(new Date(2025, 0 - 1, 1));
Because of how dates work in JavaScript, the value of the year gets rolled back if we subtract 1 month from January.

The tricky thing to remember is that months are zero-based and go from 0 (January) to 11 (December).

Further Reading #

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.