Get all Dates in a Month using JavaScript

avatar

Borislav Hadzhiev

Tue Jan 18 20222 min read

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, which takes the year and a month (zero-indexed) and returns all of the dates in the month.

The 3 parameters 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 for the given 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).

While the passed in month is equal to the month in the Date object, we want to continue to iterate and push dates to the dates array.

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 for the given date and the getMonth method the zero-based value for the month that the getAllDaysInMonth function expects.

Use the search field on my Home Page to filter through my more than 1,000 articles.