[英]between java.time.LocalTime (next day)
請建議是否提供API支持來確定我的時間是否在2個LocalTime
實例之間,或者建議使用其他方法。
我有這個實體:
class Place {
LocalTime startDay;
LocalTime endDay;
}
它存儲工作日的開始和結束時間,即從“ 9:00”到“ 17:00”,或存儲從“ 22:00”到“ 5:00”的夜總會。
我需要實現一個Place.isOpen()
方法,該方法確定該場所是否在給定時間打開。
一個簡單的isBefore
/ isAfter
在這里不起作用,因為我們還需要確定結束時間是否在第二天。
當然,我們可以比較開始時間和結束時間並做出決定,但是我想要一些沒有附加邏輯的東西,只是一個簡單的between()
調用。 如果LocalTime
不足以實現此目的,請建議其他。
如果我理解正確,則需要根據關閉時間是在開放時間的同一天(9-17)還是在隔天的開放時間(22-5)做出兩種選擇。
它可能只是:
public static boolean isOpen(LocalTime start, LocalTime end, LocalTime time) {
if (start.isAfter(end)) {
return !time.isBefore(start) || !time.isAfter(end);
} else {
return !time.isBefore(start) && !time.isAfter(end);
}
}
這對我來說看起來更干凈:
if (start.isBefore(end)) {
return start.isBefore(date.toLocalTime()) && end.isAfter(date.toLocalTime());
} else {
return date.toLocalTime().isAfter(start) || date.toLocalTime().isBefore(end);
}
我已經重構了@assylias答案,所以我從api int整數格式獲取打開和關閉小時的時間,所以使用int而不是本地時間
public static boolean isOpen(int start, int end, int time) {
if (start>end) {
return time>(start) || time<(end);
} else {
return time>(start) && time<(end);
}
}
public static boolean isOpen(int start, int end) {
SimpleDateFormat sdf = new SimpleDateFormat("HH");
Date resultdate = new Date();
String hour = sdf.format(resultdate);
int time = Integer.valueOf(hour);
if (start>end) {
return time>(start) || time<(end);
} else {
return time>(start) && time<(end);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.