I was experiencing some unexpected behaviors when doing date/time calculations. When it comes to daylight savings or leap years, the order of operations (months/days/hours) does matter, which is rather obvious. But it seems that the operation order is not deterministic when it comes to addition and substraction of java.time.Period?
To make more clear what I mean here an example, where I add and substract the same period from a date:
public static void main(String[] args) {
Period period = Period.ofDays(365).plus(Period.ofYears(1));
LocalDate dateA = LocalDate.of(2020, 4, 24);
LocalDate dateA2 = dateA.minus(period).plus(period);
LocalDate dateA3 = dateA.plus(period).minus(period);
System.out.println(dateA);
System.out.println(dateA2);
System.out.println(dateA3);
System.out.println("---");
LocalDate dateB = LocalDate.of(2022, 4, 24);
LocalDate dateB2 = dateB.minus(period).plus(period);
LocalDate dateB3 = dateB.plus(period).minus(period);
System.out.println(dateB);
System.out.println(dateB2);
System.out.println(dateB3);
}
the output is
2020-04-24
2020-04-23
2020-04-24
---
2022-04-24
2022-04-24
2022-04-23
I was expecting that addition and substraction negate each other, so adding and substracting the same Period would always result in the initial date, but it does not. (It would require to swap the execution order from years/months/days when adding to days/months/years when substracting i assume)
Is this a bug or expected?