Get the First day of the Previous Month in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 25 20212 min read

banner

Photo by S Migaj

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 parameters to the Date() constructor:

  1. The year
  2. The month - notice that we subtracted 1 from the return value of the getMonth method in order 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, meaning 0 is January and 11 is December.

We hardcoded 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee