Lega Lega -4 years ago 87
Java Question

How to parse week day name with different patterns into DayOfWeek?

I need to parse week day name into

DayOfWeek
.
Week day name may be either in short ('Mon') or long ('Monday') format.

Currently I've come up with such solution:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE", locale);
DayOfWeek dayOfWeek;
try {
dayOfWeek = DayOfWeek.from(dtf.parse(value));
}
catch (DateTimeException e) {
dtf = DateTimeFormatter.ofPattern("EEEE", locale);
dayOfWeek = DayOfWeek.from(dtf.parse(value));
}


Is there a shorter solution?

Answer Source

You can use DateTimeFormatterBuilder with optional patterns. These will be tried in the order you append them. A DateTimeException will still be thrown if all patterns fail.

final DateTimeFormatter dtf = new DateTimeFormatterBuilder()
        .appendOptional(DateTimeFormatter.ofPattern("EEEE"))
        .appendOptional(DateTimeFormatter.ofPattern("E"))
        .toFormatter(locale);

final DayOfWeek dow1 = DayOfWeek.from(dtf.parse("Mon"));
final DayOfWeek dow2 = DayOfWeek.from(dtf.parse("Monday"));

Note how the resulting DayOfWeek can now be final if you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download