假设您从某个地方以字符串的形式读取您的每日营业时间(在良好的设计中这不是必需的,但假设您的情况是这样),您首先需要一个数据结构来存储它们。我建议Map。我建议每天上课时间如下。
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);
}
}
现在我们可以通过这种方式将您的字符串读入您的地图:
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])));
为此,我们需要以下格式化程序:
private static final DateTimeFormatter dayParser = DateTimeFormatter.ofPattern("EEE", Locale.ENGLISH);
完成此操作后,我们可以随时检查我们是否在营业时间内:
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()));
}
刚刚跑步(我所在时区的星期五下午 5:40)我得到了:
现在开门了吗?真的
链接: Oracle tutorial: Date Time 解释如何使用 java.time。