News for hackers. Stuff that matters.
Re:Ask HN: Did you encounter any leap year bugs today? by javanonymous on Friday March 01, 2024 @06:28AM (#39560781)
The Java library actually supports this case.

It may not have the convenient "years" method directly, but you can add an arbitrary unit of time quite easily

Example with duration:

    Duration.of(1, ChronoUnit.YEARS)
Example with datetime:

    today.plus(2, ChronoUnit.YEARS)
It even supports decades, centuries, eras and half days :-)

For those curious about how it handles leap years:

    var leapDay = LocalDate.of(2024, 2, 29)
    leapDay.plus(1, ChronoUnit.YEARS);
   
    // ==> 2025-02-28

    var lastYear = LocalDate.of(2023, 3, 1);
    lastYear.plus(1, ChronoUnit.YEARS);

    // ==> 2024-03-01

    var lastFeb = LocalDate.of(2023, 2, 28);
    lastFeb.plus(1, ChronoUnit.YEARS);

    // ==> 2024-02-28

    var firstFeb = LocalDate.of(2024, 2, 1);
    leapDay.with(TemporalAdjusters.lastDayOfMonth());

    // ==> 2024-02-29
Re:Ask HN: Did you encounter any leap year bugs today? by rfoo on Sunday March 03, 2024 @04:25AM (#39579631)
Thanks! It does this according to doc:

    This method adds the specified amount to the years field in three steps:
      * Add the input years to the year field
      * Check if the resulting date would be invalid
      * Adjust the day-of-month to the last valid day if necessary
TIL. I didn't know that Java had a builtin calendar (instead of datetime) library.