How to Get All Dates in a Month Using JavaScript

To get all the dates in a specific month using JavaScript:

  1. Start with the first day of the desired month.
  2. Keep adding days until the next month is reached.

Example

function getAllDatesInMonth(year, month) {
  let startDate = new Date(year, month, 1); // month is 0-indexed
  let endDate = new Date(year, month + 1, 1);
 
  let dates = [];
  while (startDate < endDate) {
    dates.push(new Date(startDate)); // clone the date object
    startDate.setDate(startDate.getDate() + 1);
  }

  return dates;
}

// Usage example:
let datesInFebruary2023 = getAllDatesInMonth(2023, 1);
console.log(datesInFebruary2023);

Output

How to Get All Dates in a Month Using JavaScript

In this function, the year is full (e.g., 2023), and the month is zero-indexed (so January = 0, February = 1, etc.). The function returns an array of Date objects representing each day in the specified month.

UTC Version

When working with dates and times in JavaScript, it’s crucial to be consistent with your methods. If you initialize a date object with Date.UTC, you’re setting the date and time in Coordinated Universal Time (UTC).

To avoid unexpected results due to local timezone offsets, you should use the corresponding getUTC* methods.

function getAllDatesInMonthUTC(year, month) {
  let startDate = new Date(Date.UTC(year, month, 1)); // month is 0-indexed
  let endDate = new Date(Date.UTC(year, month + 1, 1));

  let dates = [];
  while (startDate < endDate) {
    dates.push(new Date(startDate)); // clone the date object
    startDate.setUTCDate(startDate.getUTCDate() + 1);
  }

  return dates;
}

// Usage example:
let datesInFebruary2023 = getAllDatesInMonthUTC(2023, 1); // February is month index 1

console.log(datesInFebruary2023);

Output

UTC Version

Using ES6 Array Initializer

Using modern JavaScript (ES6 and above), you can leverage array initializers and the Array.from method to achieve this more concisely.

function getAllDatesInMonthUTC(year, month) {
  const daysInMonth = new Date(Date.UTC(year, month + 1, 1))
    - new Date(Date.UTC(year, month, 1));
  return Array.from({ length: daysInMonth / (24 * 60 * 60 * 1000) }, (_, index) =>
     new Date(Date.UTC(year, month, index + 1))
  );
}

// Usage example:
let datesInFebruary2023 = getAllDatesInMonthUTC(2023, 1);

console.log(datesInFebruary2023);

Output

Using ES6 Array Initializer

That’s it!

Leave a Comment