How many days in this month
A date picker greys out the days that do not exist in the month being shown.
- Months are numbered 1 to 12.
- February has 29 days in a leap year and 28 otherwise; the leap rule is the usual 4 / 100 / 400 one.
- A month outside 1 to 12 gives 0.
daysInMonth(year: int, month: int) → int
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
int daysInMonth(int year, int month) {
}
Worked examples
| Call | Result |
|---|---|
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 Java
int daysInMonth(int year, int month) {
if (month < 1 || month > 12) return 0;
int[] table = {31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month != 2) return table[month - 1];
boolean leap = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
return leap ? 29 : 28;
}