I've got an error when I try to convert this string to date:
String s = "Mon, 11-12-2021 - 12:00";
LocalDateTime localDateTime = LocalDateTime.parse(s, DateTimeFormatter.ofPattern("EEE, MM-dd-yyyy - HH:mm"));
I got this:
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Mon, 11-12-2021 - 12:00' 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.LocalDateTime.parse(LocalDateTime.java:492)
at Main.main(Main.java:11)
Is it possible in Java to convert this string or it should be changed in some way?
CodePudding user response:
Perhaps your locale is not English. Then you would need to pass Locale.ENGLISH
to your DateTimeFormatter.
This worked for me, together with @Narcis Postolache's date change to Fri
.
String s = "Fri, 11-12-2021 - 12:00";
LocalDateTime localDateTime = LocalDateTime.parse(s, DateTimeFormatter.ofPattern("EEE, MM-dd-yyyy - HH:mm", Locale.ENGLISH));
localDateTime object: 2021-11-12T12:00
CodePudding user response:
Try
String s = "Fri, 11-12-2021 - 12:00";
CodePudding user response:
Your defaul locale is not US and 11-12-2021 is not Monday it's Friday:
String s = "Fri, 11-15-2021 - 12:00";
LocalDateTime localDateTime = LocalDateTime.parse(s,
DateTimeFormatter.ofPattern("EEE, MM-dd-yyyy - HH:mm", Locale.US));
CodePudding user response:
For the pattern you are requesting it might be a good idea to specify a different predefined formatter according to the official documentation (have a look to see the different options)
String pattern = "Mon, 11 Dec 2021 12:00:00 GMT";
LocalDate formatter = LocalDate.parse(pattern, DateTimeFormatter.RFC_1123_DATE_TIME);
Additionally, if you don't want to convert the month you can do:
LocalDateTime local = LocalDateTime.parse("2021-12-11T12:00:00");
and then get the day of the week with:
System.out.println(local.getDayOfWeek());