Of course it's possible with the Java 8 Date & Time API.
You seem to have three fields: the day-of-week, the hour-of-day and the minute-of-hour. This could normally be parsed using DateTimeFormatter::ofPattern
with the formatting string EEE HH:mm
, but the problem is that MON
(in all caps) is not standard; it should be Mon
instead.
So we need to build our formatter using the DateTimeFormatterBuilder
, instructing that the string should be parsed in a case-insensitive manner:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("EEE HH:mm")
.toFormatter(Locale.ROOT);
The only thing to do is parsing the fields using
TemporalAccessor parsed = formatter.parse(elem);
Now parsed
contains the abovementioned parsed fields.
To a datetime
Of course, you don't have to convert this to an actual date. There are many use cases where one don't want a date, but rather only a day-of-week and the time. This is an example.
But if you, for example, want to get the current date and adjust it to match the data from your schedule, you can do something like this:
TemporalAdjuster adj = TemporalAdjusters.nextOrSame(DayOfWeek.of(parsed.get(ChronoField.DAY_OF_WEEK)));
LocalDateTime now = LocalDate.now()
.atTime(LocalTime.from(parsed))
.with(adj);