Get all Dates in a Month using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 24, 2022

banner

Photo from Unsplash

Get all Dates in a Month using JavaScript #

To get all dates in a month:

  1. Create a new Date object that stores the first date of the given month.
  2. Iterate over all of the dates in the specific month.
  3. Push each Date object to an array.
index.js
function getAllDaysInMonth(year, month) { const date = new Date(year, month, 1); const dates = []; while (date.getMonth() === month) { dates.push(new Date(date)); date.setDate(date.getDate() + 1); } return dates; } const now = new Date(); // 👇️ all days of the current month console.log(getAllDaysInMonth(now.getFullYear(), now.getMonth())); const date = new Date('2022-03-24'); // 👇️ All days in March of 2022 console.log(getAllDaysInMonth(date.getFullYear(), date.getMonth()));
We created a reusable function that takes the year and a month (zero-indexed) and returns all the dates in the given month.

The 3 arguments we passed to the Date() constructor are:

  1. year - a four-digit number that represents the year of the date.
  2. month - a zero-indexed number that represents the month (0 = January, 1 = February, etc).
  3. day of the month - the day of the month of the date.

We created a Date object that stores the date for the first day of the month.

The getMonth method returns the month of the specified date as a zero-based value (January = 0, December = 11).

We want to continue to iterate and push dates into the dates array while the passed in month is equal to the month in the Date object.

The setDate method changes the day of the month for the given Date instance in place.

On each iteration, we set the date to the next day of the month until we reach the next month.

Once we reach the next month, the condition in the while loop is no longer met and the dates array is returned from the function.

If you have a date string and not a Date object, you can pass the string to the Date() constructor to get a Date object, from which you can get the year and month when calling the getAllDaysInMonth function.

index.js
function getAllDaysInMonth(year, month) { const date = new Date(year, month, 1); const dates = []; while (date.getMonth() === month) { dates.push(new Date(date)); date.setDate(date.getDate() + 1); } return dates; } const date = new Date('2022-03-24'); // 👇️ All days in March of 2022 console.log(getAllDaysInMonth(date.getFullYear(), date.getMonth()));

The getFullYear method returns the four-digit year of the given date and the getMonth method returns the zero-based value of the month.

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.