ps0604
ps0604

Reputation: 1081

Shifting month/day automatically when constructing LocalDate

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?

Upvotes: 4

Views: 365

Answers (2)

Twister
Twister

Reputation: 161

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))

Upvotes: 3

Matias Fuentes
Matias Fuentes

Reputation: 461

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);

Upvotes: 6

Related Questions