Get First and Last Day of the Current Month in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 25 20212 min read

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

  1. The year
  2. The month
  3. The day - 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 that corresponds to a date.

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

Getting the first day of the month is straight forward, we got the current year and month and hardcoded 1 for the day.

To get the last day of the month, we added 1 to the return value from the getMonth method. This gets us the next month.

This balances out, because we set the day 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.

When using this approach to get the last day of other months, always keep in mind 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