Drill

ProblemsTypeScript › dates

How many days in this month

easydatesTypeScript

A date picker greys out the days that do not exist in the month being shown.

daysInMonth(year: int, month: int) → int

Solve it in the editor →

Where you start

function daysInMonth(year: number, month: number): number {
  
}

Worked examples

CallResult
daysInMonth(2024, 2)29
daysInMonth(2023, 2)28
daysInMonth(1900, 2)28
daysInMonth(2024, 4)30

Hint

A lookup table for the eleven easy months, and one branch for February.

Reference solution in TypeScript
function daysInMonth(year: number, month: number): number {
  if (month < 1 || month > 12) return 0;
  const table = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  if (month !== 2) return table[month - 1];
  const leap = year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
  return leap ? 29 : 28;
}

The same problem in another language

More dates problems in TypeScript