Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 LocalDate parse Exception

Tags:

java

java-8

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

like image 727
drenda Avatar asked May 26 '14 15:05

drenda


1 Answers

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"));
like image 140
assylias Avatar answered Nov 03 '22 00:11

assylias