Assuming that you are reading your daily opening hours as strings from somewhere (which in a good design should not be necessary, but assuming that in your case it is), you first need a data structure for storing them. I suggest a Map
. And I suggest a class like the following for the daily hours.
public class DailyHours {
private static final DateTimeFormatter timeParser = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("h:mm a")
.toFormatter(Locale.ENGLISH);
private LocalTime opens;
private LocalTime closes;
public DailyHours(String times) {
String[] hours = times.split(" - ");
if (hours.length != 2) {
throw new IllegalArgumentException("Improper format " + times + ", must be like 11:00 am - 9:00 pm");
}
opens = LocalTime.parse(hours[0], timeParser);
closes = LocalTime.parse(hours[1], timeParser);
}
public boolean isBetween(LocalTime time) {
return ! time.isBefore(opens) && time.isBefore(closes);
}
}
Now we can read your strings into your map in this way:
String[] openingHoursTable = {
"Mon, 11:00 am - 9:00 pm",
"Tue, 11:00 am - 9:00 pm",
"Wed, 11:00 am - 9:00 pm",
"Thu, 11:00 am - 9:00 pm",
"Fri, 11:00 am - 9:00 pm"
};
Map<DayOfWeek, DailyHours> hoursPerDay = Arrays.stream(openingHoursTable)
.map(s -> s.split(", "))
.collect(Collectors.toMap(arr -> DayOfWeek.from(dayParser.parse(arr[0])),
arr -> new DailyHours(arr[1])));
For this we need the following formatter:
private static final DateTimeFormatter dayParser = DateTimeFormatter.ofPattern("EEE", Locale.ENGLISH);
Once we have done this, we can check whether we are within the opening hours as often as we want:
ZonedDateTime currentTime = ZonedDateTime.now(ZoneId.systemDefault());
DailyHours todaysHours = hoursPerDay.get(currentTime.getDayOfWeek());
if (todaysHours == null) {
System.out.println("Closed today");
} else {
System.out.println("Open now? " + todaysHours.isBetween(currentTime.toLocalTime()));
}
Running just now (Friday 5:40 PM in my time zone) I got:
Open now? true
Link: Oracle tutorial: Date Time explaining how to use java.time.