Leap Year Check and Days in a Month
Apply Gregorian leap-year rules and return the exact number of days in any month, including February in leap and common years.
Code
export function isLeapYear(year) {
if (!Number.isInteger(year) || year < 1 || year > 9999) {
throw new RangeError("year must be an integer between 1 and 9999");
}
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
export function daysInMonth(year, month) {
if (!Number.isInteger(month) || month < 1 || month > 12) {
throw new RangeError("month must be an integer between 1 and 12");
}
const lengths = [
31,
isLeapYear(year) ? 29 : 28,
31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
];
return lengths[month - 1];
}Report a problem with this exampleOpens a pre-filled issue on GitHub.