判断时间是否在某个时间段内
2022-09-07 本文已影响0人
平面小狮子
判断当前时间是否在时间段内(可隔天,也可不隔天)
public class TimeIntervalUtil {
/**
* 判断时间是否在某个时间段内
*
* @param nowTime 需要判断的时间,形如23:30:00 (可为空)
* @param startTime 时间段开始时间,形如22:30:00
* @param endTime 时间段结束时间,形如06:00:00
* @return boolean
*/
public static boolean isInTimeRange(String nowTime, String startTime, String endTime) {
// 时间为空,默认赋值当前时间(时分秒)
if (StrUtil.isBlank(nowTime)) {
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("HH:mm");
nowTime = LocalDateTime.now().format(pattern);
}
int set = Integer.valueOf(nowTime.replaceAll(":", ""));
int begin = Integer.valueOf(startTime.replaceAll(":", ""));
int end = Integer.valueOf(endTime.replaceAll(":", ""));
if (begin > end) {
return set < end || set > begin;
} else {
return set > begin && set < end;
}
}
public static void main(String[] args) throws ParseException {
boolean inTimeRange = isInTimeRange("11:50", "20:00", "08:00");
System.out.println(inTimeRange);
String str = DateTime.now().toTimeStr();
System.out.println(str);
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("HH:mm");
String format = LocalDateTime.now().format(pattern);
System.out.println(format);
boolean inTimeRange1 = isInTimeRange(format, "20:00", "08:00");
System.out.println(inTimeRange1);
DateTime dateTime = DateUtil.endOfDay(DateUtil.date());
System.out.println(dateTime);
}
}