Get the Number of Days in a Month in JavaScript

To get the number of days in a month, read Temporal.PlainDate.from({year, month, day: 1}).daysInMonth — it returns 28 or 29 for February automatically. Part of Leap Year Algorithms.

Why this scenario is tricky

Days-in-month is really the leap-year question in disguise: only February varies, and only by the leap-year rule. A hard-coded [31,28,31,...] table is wrong every fourth year. Temporal exposes the answer as a property so you never re-implement the rule.

February is the only variableA fixed table is wrong in leap yearsFebruary is the only variable[31,28,31,...] lookupFeb wrong every leap yearPlainDate.daysInMonth28 or 29 automaticallydaysInMonth encodes the leap-year rule so you don't hard-code February.

Minimal working solution

import { Temporal } from '@js-temporal/polyfill';
const n = Temporal.PlainDate.from({ year: 2024, month: 2, day: 1 }).daysInMonth; // 29

Days in a monthdaysInMonth reads it off a PlainDateDays in a monthyear, monthPlainDate.fromdaysInMonth

Full production version

// Legacy trick: day 0 of the next month is the last day of this month.
function daysInMonth(year: number, month1to12: number): number {
  return new Date(year, month1to12, 0).getDate(); // month is 1-based here by design
}

Legacy day-0 tricknew Date(y, m, 0) is last day of month mLegacy day-0 trickyear, monthDate(y,m,0)getDate()day count

Verification snippet

Get the Number of Days in a Month in JavaScript — assertionsKey cases assert correctlyAssertions that prove the edge caseFeb 202429Feb 202328April30Feb 200029

Common pitfalls

Days in a Month pitfallsCommon mistakes and their fixesWrongRighthard-coded 28 for Febwrong in leap yearsPlainDate.daysInMonthleap-awaregetMonth() off-by-onewrong month queriedday 0 of next monthlast day trick

Frequently Asked Questions

How do I get the number of days in a month?

Read Temporal.PlainDate.from({year, month, day: 1}).daysInMonth. It returns 30 or 31 for fixed months and 28 or 29 for February according to the leap-year rule, so you never hard-code the count.

What is the new Date(year, month, 0) trick?

Day 0 of a month is the last day of the previous month, so new Date(year, month, 0).getDate() gives the number of days in that month. Note the month argument here is effectively 1-based because you are asking for the month before month+1.