package com.xiaopeng.map.utils;
|
|
import com.alibaba.fastjson2.JSON;
|
import com.alibaba.fastjson2.JSONArray;
|
|
import java.time.LocalTime;
|
import java.time.format.DateTimeFormatter;
|
|
public class TimeRangeChecker {
|
|
public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");
|
|
/**
|
* 判断当前时间是否在时间段内
|
* @param jsonArrayStr JSON数组字符串,格式如 ["08:00-12:00", "13:30-17:30", "18:00-21:00"]
|
* @return true 如果在时间段内,false 如果不在
|
*/
|
public static boolean isCurrentTimeInRanges(LocalTime now,String jsonArrayStr) {
|
return isTimeInRanges(jsonArrayStr, now);
|
}
|
|
/**
|
* 判断指定时间是否在时间段内
|
* @param jsonArrayStr JSON数组字符串
|
* @param time 要判断的时间
|
* @return true 如果在时间段内,false 如果不在
|
*/
|
public static boolean isTimeInRanges(String jsonArrayStr, LocalTime time) {
|
if (jsonArrayStr == null || jsonArrayStr.isEmpty()) {
|
return false;
|
}
|
|
try {
|
// 直接解析为JSONArray
|
JSONArray timeArray = JSON.parseArray(jsonArrayStr);
|
if (timeArray == null || timeArray.isEmpty()) {
|
return false;
|
}
|
|
// 遍历所有时间段
|
for (int i = 0; i < timeArray.size(); i++) {
|
String timeRange = timeArray.getString(i);
|
if (isTimeInRange(time, timeRange)) {
|
return true;
|
}
|
}
|
|
return false;
|
|
} catch (Exception e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
|
/**
|
* 判断时间是否在单个时间段内
|
*/
|
private static boolean isTimeInRange(LocalTime time, String timeRange) {
|
if (timeRange == null || !timeRange.contains("-")) {
|
return false;
|
}
|
|
String[] parts = timeRange.split("-");
|
if (parts.length != 2) {
|
return false;
|
}
|
|
try {
|
LocalTime start = LocalTime.parse(parts[0].trim(), TIME_FORMATTER);
|
LocalTime end = LocalTime.parse(parts[1].trim(), TIME_FORMATTER);
|
|
// 处理跨天的情况(如 22:00-02:00)
|
if (end.isBefore(start)) {
|
// 跨天时间段
|
return !time.isBefore(start) || !time.isAfter(end);
|
} else {
|
// 正常时间段
|
return !time.isBefore(start) && !time.isAfter(end);
|
}
|
} catch (Exception e) {
|
return false;
|
}
|
}
|
}
|