Mon Oct 25 2021·2 min read
Photo by Ansgar Scheffold
To get the first and last day of the current month, use the
getMonth() methods to get the current year and month and pass them to the
Date() constructor to get an object representing the two dates.
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:
0means 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.
returns an integer between
0 (January) and
11 (December) and represents
the month for a given date. Yes, unfortunately the
getMonth method is off
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
means - give me the last day of the prior month.
1month forward and
1day back to get the last day of the current 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