-2

Please! I would like to understand why this simple LocalDate parsing isn't working!

My DateFormatter works (in both ways), but when I'm trying to parse into a new LocalDate variable (using the same Formatter), it doesn't work and I get the following exception.

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MMM-dd-yyyy"); 
LocalDate date = LocalDate.now();
String dateFormatted = date.format(dateTimeFormatter); 

System.out.println("Data formatted > " + dateFormatted); 
String dateFormatted1 = dateTimeFormatter.format(date); 
System.out.println("Data formatted  2> " + dateFormatted1); 

LocalDate dateParsed = LocalDate.parse(dateTimeFormatter.format(date));
System.out.println("Data parsed > " + dateParsed); 

LocalDate dateParsed2 = LocalDate.parse(dateFormatted, dateTimeFormatter); 
System.out.println("Data parsed 2 > " + dateParsed2);

/////////////////////// Exception //////////////////////////////

Caused by: java.time.format.DateTimeParseException: Text 'dez-11-2017' could not be parsed at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDate.parse(LocalDate.java:400)
    at java.time.LocalDate.parse(LocalDate.java:385)
    at hypercaos.AddController.initialize(AddController.java:74)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)*
Ole V.V.
  • 65,573
  • 11
  • 96
  • 117
Erick Cabral
  • 109
  • 6

1 Answers1

2

Let the function know which one is the formatter:

LocalDate dateParsed = LocalDate.parse(dateTimeFormatter.format(date), dateTimeFormatter);

When you parse without the Formatter, LocalDate will understand it as yyyy-MM-dd, and your String is MMM-dd-yyyy.

KL_
  • 1,473
  • 1
  • 6
  • 13
  • Thanks! it worked. Actually, I made a mistake. I thought that doing that, I could capture the variable dateParsed in MMM-dd-yyyy format already (to show it later without doing LocalDate -> String format conversion). But what it does is just turn to yyyy-MM-dd again. Thank you! Ps.: Sorry about the silly question!! :-) – Erick Cabral Dec 12 '17 at 17:02