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.
Minimal working solution
import { Temporal } from '@js-temporal/polyfill';
const n = Temporal.PlainDate.from({ year: 2024, month: 2, day: 1 }).daysInMonth; // 29
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
}
Verification snippet
Common pitfalls
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.