Bibi541 Bibi541 - 5 months ago 25
Java Question

Java java.time.format.DateTimeParseException on String

I am trying to parse a date to convert it to epochs. I tried the solution of a similar question here without success:

String date = "Jun 4 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("LLL dd yyyy").withLocale(Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(date, formatter);
System.out.println(date+" "+ldt.toEpochSecond(ZoneOffset.UTC));


And I get
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Jun 4 2015' could not be parsed at index 0
even though I am fairly certain that my regular expression is correct. What am I missing here?

EDIT:

Following the comments, I changed LocalDateTime to LocalDate, but keep getting the same error:

String date = "Jun 4 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy").withLocale(Locale.ENGLISH);
LocalDate ldt = LocalDate.parse(date, formatter);

Answer
    String date = "Jun 4 2015";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy").withLocale(Locale.ENGLISH);
    LocalDate ldt  = LocalDate.parse(date, formatter);

parses fine. Don't put the "dd" as it won't parse days less than 10. As @JB Nizet said, you'll need to use LocalDate, not LocalDateTime.