Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting month/day automatically when constructing LocalDate

Tags:

java

java-8

This code

LocalDate date = LocalDate.of(2019, 4, 31);

Throws this error:

java.time.DateTimeException: Invalid date 'APRIL 31'

What I need is to construct a date based on a given number of days, 31 in this case, but since April only has 30 days I get the exception. In the example above, I should get May 1, is this feasible to do with the java.time library or needs to be coded manually?

like image 220
ps0604 Avatar asked Mar 05 '23 04:03

ps0604


2 Answers

As I mentioned in the comments, It would probably be easier if you added days to a base date, like this:

LocalDate.of(2019,4,1).plusDays(31);
like image 93
Matias Fuentes Avatar answered Mar 15 '23 05:03

Matias Fuentes


If you really want to do that, you can try this instead of plusDay:

LocalDate.parse("2018-04-31", DateTimeFormatter.ISO_LOCAL_DATE.withResolverStyle(ResolverStyle.LENIENT))
like image 38
Twister Avatar answered Mar 15 '23 06:03

Twister