isLeapYear
Determines whether the given year is a leap year.
1/**
2 * Determines whether the given year is a leap year.
3 *
4 * @param yearOrDate - The year as a number or a Date object.
5 * @returns True if it's a leap year, false otherwise.
6 *
7 * @example
8 * isLeapYear(2024) // true
9 * isLeapYear(new Date('2000-01-01')) // true
10 */
11export function isLeapYear(yearOrDate: number | Date): boolean {
12 const year = yearOrDate instanceof Date ? yearOrDate.getFullYear() : yearOrDate;
13
14 return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
15}
Dual Input Support
Accepts either a
Date
object or a plainnumber
, increasing flexibility and ease of use.Accurate Leap Year Logic
Implements the correct rule for leap years, including exceptions for centuries not divisible by 400.
Pure and Deterministic
Has no side effects and always produces the same output for the same input.
Compact and Readable
The implementation is short, efficient, and easy to understand or audit.
Tests | Examples
1test('identifies leap year by number', () => {
2 expect(isLeapYear(2024)).toBe(true);
3});
4
5test('identifies non-leap year by number', () => {
6 expect(isLeapYear(2023)).toBe(false);
7});
8
9test('identifies leap year by Date object', () => {
10 expect(isLeapYear(new Date('2000-02-29'))).toBe(true);
11});
12
13test('identifies non-leap year by Date object', () => {
14 expect(isLeapYear(new Date('2100-01-01'))).toBe(false);
15});
Common Use Cases
Calendar Utilities
Determine whether February should have 28 or 29 days when generating date pickers.
Date Validation
Validate date input for leap years (e.g., disallow February 29 on non-leap years).
Scheduling Logic
Adjust recurring annual schedules or billing cycles in leap years.
Data Normalization
Handle edge cases for datasets with February 29 entries.