Description
The dateAddMonths() methods can be simplified by using the plusMonths() method of Java 8 LocalDate:
LocalDate.ofEpochDay(days).plusMonths(months)
This method adds the specified amount to the months field in three steps:
- Add the input months to the month-of-year field
- Check if the resulting date would be invalid
- Adjust the day-of-month to the last valid day if necessary
For example, 2019-01-31 plus one month would result in the invalid date 2019-02-31. Instead of returning an invalid result, the last valid day of the month, 2019-02-28, is selected instead.
The valid result is returned as is. For example, adding 1 month to 2019-02-28 is 2019-03-28.
Mysql and PostgreSQL have the same behavior:
mysql> SELECT DATE_ADD("2019-01-31", INTERVAL 1 MONTH); +------------------------------------------+ | DATE_ADD("2019-01-31", INTERVAL 1 MONTH) | +------------------------------------------+ | 2019-02-28 | +------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT DATE_ADD("2019-02-28", INTERVAL 1 MONTH); +------------------------------------------+ | DATE_ADD("2019-02-28", INTERVAL 1 MONTH) | +------------------------------------------+ | 2019-03-28 | +------------------------------------------+ 1 row in set (0.00 sec)
maxim=# SELECT DATE_ADD("2019-01-31", INTERVAL 1 MONTH); ERROR: syntax error at or near "1" LINE 1: SELECT DATE_ADD("2019-01-31", INTERVAL 1 MONTH); ^ maxim=# SELECT DATE '2019-01-31' + INTERVAL '1 month'; ?column? --------------------- 2019-02-28 00:00:00 (1 row) maxim=# SELECT DATE '2019-02-28' + INTERVAL '1 month'; ?column? --------------------- 2019-03-28 00:00:00 (1 row)