drenda
drenda

Reputation: 6244

Java8 LocalDate parse Exception

I'm doing a simple parse of a string in LocalDate:

log.debug("----->" + DateTimeFormatter.ofPattern("EEE").format(LocalDateTime.now()));
    log.debug("--->" +   LocalDate.parse("lun",DateTimeFormatter.ofPattern("EEE",Locale.ITALY)));

Unfortunally, this code give this exception:

java.time.format.DateTimeParseException: Text 'lun' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfWeek=1},ISO of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1919)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1854)
at java.time.LocalDate.parse(LocalDate.java:400)
at it.Main.main(Main.java:60)
 ... 11 more
     Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {DayOfWeek=1},ISO of type java.time.format.Parsed
at java.time.LocalDate.from(LocalDate.java:368)
at java.time.LocalDate$$Lambda$15/42768293.queryFrom(Unknown Source)
at java.time.format.Parsed.query(Parsed.java:226)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1850)
... 13 more
      Exception running application it.Main

The fact is quite strange. Infact with numeric date and coherent pattern all works. Before I used java.util.Date and the same pattern and all worked without problems.

Have you some hints about this problem?

Thanks

Upvotes: 7

Views: 9973

Answers (2)

assylias
assylias

Reputation: 328629

LocalDate is supposed to represent an actual date - you only pass a day name (Monday) which can't be translated into a proper 26-May-2014, for example.

If all you want is to parse the day of week, you can use:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE", Locale.ITALY);
DayOfWeek day = DayOfWeek.from(fmt.parse("lun"));

Upvotes: 9

drenda
drenda

Reputation: 6244

Using

DateTimeFormatter.ofPattern("EEE").parse("lun").get(ChronoField.DAY_OF_WEEK);

works!

Upvotes: 0

Related Questions