Reputation: 130
I am trying to parse my date it works for most of the months but for some reason, it doesn't work for April but on the other hand, it works for juin
Locale locale = Locale.FRANCE;
DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().appendPattern("dd MMM yyyy (HH:mm)").toFormatter(locale);
LocalDateTime dateTime1 = LocalDateTime.parse(, dateTimeFormatter);
LocalDateTime dateTime2 = LocalDateTime.parse(, dateTimeFormatter);
if(dateTime1.compareTo(dateTime2) < 0) {
System.out.println("true");
} else {
System.out.println("false");
}
java.time.format.DateTimeParseException: Text '01 avril 2021 (09:40)' could not be parsed at index 3
Is there still something wrong with my pattern
19 déc. 2019 (21:15)
10 févr. 2020 (07:58)
Upvotes: 1
Views: 135
Reputation: 1540
You can define multiple optional sections for DateTimeFormatter. Keep in mind that with this configuration also "" or "01 avril 2021 (09:40)01 avr. 2021 (09:40)" would be valid (thanks to @Michael for the clarification).
public class FormatTest {
public static void main(String[] args) {
test("01 avril 2021 (09:40)");
test("01 avr. 2021 (09:40)");
test("19 déc. 2019 (21:15)");
test("19 décembre 2019 (21:15)");
test("10 févr. 2020 (07:58)");
}
private static void test(String value) {
Locale locale = Locale.FRANCE;
DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
.appendPattern("[dd MMMM yyyy (HH:mm)][dd MMM yyyy (HH:mm)]").toFormatter(locale);
LocalDateTime dateTime1 = LocalDateTime.parse(value, dateTimeFormatter);
System.out.println(dateTime1);
}
}
Upvotes: 1
Reputation: 44150
Your current pattern only works for parsing those dates when the short form of the month is the same as the long form. The short form of 'juin' is the same as the long form because it's already a short word; it doesn't need to be shortened further.
The short form of 'avril' is 'avr'. The parser is currently expecting the latter.
You need to change your pattern to use the long form if you want to parse full words. To use the long form in a pattern, use 4 Ms rather than 3: dd MMMM yyyy (HH:mm)
If the format of the month is variable then you can write your own logic around the formatter. It's not entirely clear to me what format you actually expect but this should give you the general idea:
String input = // whatever
String[] tokens = input.split(" ");
if (tokens.length != 4) throw new RuntimeException("Invalid format");
String monthToken = tokens[1];
if (monthToken.length() > 4) {
// parse with full month
}
else {
// parse with short month
}
Upvotes: 0