-2

I am trying to parse a string "Sunday, July 4, 2021" to LocalDate as the following:

string this.selectedDate = "Sunday, July 4, 2021";
LocalDate date = LocalDate.parse(this.selectedDate);

But I am getting this error:

java.time.format.DateTimeParseException: Text 'Sunday, July 4, 2021' could not be parsed at index 0

How can I convert such a string full date to the LocalDate?

Hakan Dilek
  • 2,178
  • 2
  • 23
  • 35
Khaled
  • 345
  • 5
  • 14
  • 2
    You should use the overload of `parse` that accepts a `DateTimeFormatter`, having created a formatter for the format you're using. – Jon Skeet Jul 04 '21 at 13:37
  • What did your search turn up? I’m confident that this is described in many places already. – Ole V.V. Jul 04 '21 at 14:00
  • [Java 8 – How to convert String to LocalDate](https://mkyong.com/java8/java-8-how-to-convert-string-to-localdate/). [I downvoted because research must be done to ask a good question](http://idownvotedbecau.se/noresearch/). – Ole V.V. Jul 04 '21 at 14:17
  • Tip: Learn about using [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) formats for exchanging date-time values as text. You really should not be exchanging localized strings. – Basil Bourque Jul 04 '21 at 17:17

1 Answers1

5

Try it like this.

String s = "Sunday, July 4, 2021";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEEE, LLLL d, yyyy");
LocalDate ld =  LocalDate.parse(s, dtf);
System.out.println(ld);

prints

2021-07-04

Read up on DateTimeFormatter if you want to change the output format.

Note: If the day of the week is wrong for the numeric day of the month, you will get a parsing error. To avoid this, just skip over or otherwise ignore the day of the week.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • 1
    Please give explicit locale with your formatter (use the two-arg `of` method). Ekse the code will suddenly fail if run on a computer or JVM with non-English default locale. – Ole V.V. Jul 04 '21 at 14:02
  • Good. **Suggestion for improvement**: As already pointed out by @OleV.V., [Never use SimpleDateFormat or DateTimeFormatter without a Locale](https://stackoverflow.com/a/65544056/10819573). Also, any reason why you chose `L` over `M` (which is easier to understand)? In the case of `y` and `u`, [I prefer `u` to `y`](https://stackoverflow.com/a/65928023/10819573) and it has a strong reason. – Arvind Kumar Avinash Jul 04 '21 at 14:09