Foldable.dev

Web Development

Find The Number of Days In A Month Using JavaScript

Dates in JavaScript are notoriously difficult to work with. There's a number of library dedicated to improving the experience, but sometimes it's fun to come up with a solution from scratch.

function getNumberOfDaysInMonth(someDate) {
  const lastDayOfMonth = new Date(
    someDate.getFullYear(),
    someDate.getMonth() + 1,
    0
  );

  return lastDayOfMonth.getDate();
}

const dateToday = new Date(Date.now());
console.log(dateToday.toString());
console.log(getNumberOfDaysInMonth(dateToday));
Check your browser's console log for the result of this code!