You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

时间区间判断逻辑异常:始终返回0无法触发告警求助

问题根源:时间数值的转换不匹配

你遇到的核心问题是时间格式转换的不一致,导致当前时间的数值和设定的起止时间数值不在同一个量级上,永远无法满足区间判断条件。

具体分析:

  • 对于start = 07:00:00,你通过start.replace(":", "")得到字符串"070000",转成int后是70000;同理end=17:00:00会变成170000。
  • 但你计算当前时间t的时候,用的是c.get(Calendar.HOUR_OF_DAY) * 100 + c.get(Calendar.MINUTE),比如7点整的话t是700,17点整是1700。

你可以看到,700和70000、1700和170000完全不是一个量级的数值,所以t >= from或者t <= to的条件永远不会成立,isBetween自然一直是false,a也就始终为0,触发不了alert_f()。

额外的逻辑优先级问题:

你的布尔表达式还存在优先级隐患:||的优先级低于&&,所以原表达式会被解析成:

(to > from && t >= from && t <= to) || (to < from && t >= from) || t <= to

这和你原本想表达的跨天区间判断逻辑不符,必须给跨天的判断部分加上括号。

修正方案:

统一时间数值的转换规则,要么都包含秒,要么都只保留小时和分钟。这里给你两种可行的修正方式:

方式1:保留时分秒的完整转换

把当前时间t也转换成包含时分秒的整数:

assert start != null;
int from = Integer.valueOf(start.replace(":", ""));
assert end != null;
int to = Integer.valueOf(end.replace(":", ""));

Calendar c = Calendar.getInstance();
int hours = c.get(Calendar.HOUR_OF_DAY);
int minutes = c.get(Calendar.MINUTE);
int seconds = c.get(Calendar.SECOND);
// 转换成时分秒的整数,比如7:00:00就是70000,和from/to格式一致
int t = hours * 10000 + minutes * 100 + seconds;

// 给逻辑加上括号,明确优先级
boolean isBetween = (to > from && t >= from && t <= to) || (to < from && (t >= from || t <= to));
int a = isBetween ? 1 : 0;
if(a == 1) {
    alert_f();
}

方式2:只保留小时和分钟(忽略秒)

把from和to也转换成只包含小时和分钟的整数:

assert start != null;
// 只取前5位(时分),转成整数,比如07:00:00变成700
int from = Integer.valueOf(start.substring(0,5).replace(":", ""));
assert end != null;
int to = Integer.valueOf(end.substring(0,5).replace(":", ""));

Calendar c = Calendar.getInstance();
int t = c.get(Calendar.HOUR_OF_DAY) * 100 + c.get(Calendar.MINUTE);

// 修正逻辑括号
boolean isBetween = (to > from && t >= from && t <= to) || (to < from && (t >= from || t <= to));
int a = isBetween ? 1 : 0;
if(a == 1) {
    alert_f();
}

两种方式都能解决你的问题,选哪种取决于你是否需要精确到秒的判断。

内容的提问来源于stack exchange,提问作者RGS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:35:32