liujie
2026-02-27 1842363569f0ac34f5736ce80903a26eeb39be0f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.xiaopeng.operation.utils;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
 
public class TimeRangeChecker {
    
    private 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;
        }
    }
}