Get First and Last Day of the Current Month in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get First and Last Date of the Current Month #

To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates.

index.js
const now = new Date(); const firstDay = new Date(now.getFullYear(), now.getMonth(), 1); console.log(firstDay); // 👉️ Sat Oct 01 2022 ... const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0); console.log(lastDay); // 👉️ Mon Oct 31 2022 ...

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

  1. The year
  2. The month
  3. The day of the month - 0 means give me the last day of the previous month.

We used the following 2 date-related methods:

  • Date.getFullYear method - returns a four-digit number representing the year of a given date.

  • Date.getMonth - returns an integer between 0 (January) and 11 (December) and represents the month of a given date. Yes, unfortunately the getMonth() method is off by 1.

Getting the first day of the month is straight forward. We have to get the current year, the current month and hardcode 1 for the day of the month.
index.js
const now = new Date(); const firstDay = new Date(now.getFullYear(), now.getMonth(), 1); console.log(firstDay); // 👉️ Sat Oct 01 2022 ...

We added 1 to the return value of the getMonth method to get the next month.

index.js
const now = new Date(); const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0); console.log(lastDay); // 👉️ Mon Oct 31 2022 ...

Lastly, we set the day of the month to 0. Setting the day to 0 means - give me the last day of the prior month.

We basically go 1 month forward and 1 day back to get the last day of the current month.

Because of how dates get rolled back in JavaScript, this is a pretty good solution for getting the last day of the month.

Always keep in mind that months are zero-based and go from 0 (January) to 11 (December) when using this approach to get the last day of other months.

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.