Easy Way to Get the Number of Days in a Month

Working with dates in JavaScript has a bit of a reputation for being messy. The Date object isn’t the most intuitive thing in the language, and even a simple task like figuring out how many days are in a month can seem harder than it should be.

But here’s the good news: there's a surprisingly simple trick to get the number of days in any month using just one line of code. Let’s break it down in a way that makes sense, with examples.

Why is this Tricky?

It’s good to understand why this isn't as straightforward as you might think.

  • Some months have 30 days, some 31.

  • February has 28 or 29, depending on the year (leap years).

The solution is to use Day 0 to go backwards; JavaScript have date math magic we can use.

In JavaScript, you can create a Date object like this:

new Date(year, monthIndex, day);

Here’s the weird but useful part: if you set the day to 0, JavaScript gives you the last day of the previous month.

So if you want to find out how many days are in February 2024, this trick gives you the answer.

new Date(2024, 2, 0);

This doesn't give you a day in March, it gives you the last day of February. That’s February 29, 2024 — which is a leap year.

The One-Liner Magic

function getDaysInMonth(year, month) {
  return new Date(year, month, 0).getDate();
}

How It Works:

  • we count months from 1 (Jan = 1), but JavaScript uses 0-based months (Jan = 0).

  • So if you pass in (2024, 2), JavaScript interprets this as March 0, which gives you the last day of February.

  • .getDate() then pulls out the day of the month, which is your answer.

getDaysInMonth(2024, 2); // 29 (Leap year!)
getDaysInMonth(2023, 2); // 28
getDaysInMonth(2023, 1); // 31 (January)
getDaysInMonth(2023, 4); // 30 (April)

If you want to get days in May, pass in 5 (because month = 5 means June, and day 0 gives you the last day of May). It’s a bit odd at first, but once you get used to it, this method becomes second nature.

Final Thoughts

Date handling in JavaScript isn’t always intuitive, but little tricks like this can make your life easier. Whether you're validating forms, setting up calendars, or building scheduling tools, this method will save you time and confusion.

Article Tag  JavaScript

Share this article:

Stay Updated

    More Articles


    I write about accessibility, performance, JavaScript and workflow tooling. If my articles have helped or inspired you in your development journey, or you want me to write more, consider supporting me.