All 15 Java Date & Time API (java.time) questions
More in Java Date & Time API (java.time)
Advertisement
Back to results for “Fundamentals”
Java › Java Date & Time API (java.time)

How would you determine whether a given year is a leap year, and calculate the number of days in a specific month, using the java.time API's built-in support rather than hand-writing this classic calendrical logic?

Intermediate

Answer

Year.isLeap(yearValue) (a static method) or an existing LocalDate/YearMonth instance's isLeapYear() method correctly determines leap-year status following the standard Gregorian calendar rule (divisible by 4, except centuries not divisible by 400) without requiring you to hand-implement this classic but easy-to-get-subtly-wrong rule yourself; YearMonth.lengthOfMonth() returns the correct number of days for a specific year/month combination, automatically accounting for leap-year February correctly, both being simple, well-tested utility methods that eliminate an entire category of manual calendrical-logic bugs.
boolean isLeap = Year.isLeap(2024);  // true
boolean isLeap2 = Year.of(2024).isLeap();  // equivalent, true

YearMonth february2024 = YearMonth.of(2024, 2);
System.out.println(february2024.lengthOfMonth());  // 29, correctly leap-year-aware

YearMonth february2023 = YearMonth.of(2023, 2);
System.out.println(february2023.lengthOfMonth());  // 28, correctly non-leap-year-aware
Real-world example A calendar-rendering feature displaying the correct number of day cells for each month uses YearMonth.lengthOfMonth() rather than hand-writing the classic (and easy to get subtly wrong, especially the century-divisible-by-400 exception) leap-year calculation logic, trusting the well-tested standard library implementation instead.

Common follow-ups: What's the specific Gregorian calendar rule exception (century years) that a naive 'divisible by 4' leap-year check would incorrectly get wrong?;How does YearMonth differ from simply using LocalDate with a placeholder day value for representing a year-month combination?