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

Java时间差计算扩展需求:求中间时间与昼夜判断

实现昼夜判断的解决方案

嘿,你已经把时间差计算和中间时间的基础逻辑搞定了,要加这个昼夜判断其实很简单~按照你的需求,咱们只需要把开始时间和结束时间转换成当天的总分钟数,加起来之后和18:00对应的分钟数(也就是1080分钟)对比就行,直接用if语句就能实现。

先把你的现有代码补全并加入判断逻辑,完整代码如下:

for (int i = 1, n = licenseplateList.size(); i < n; i++) {
    try {
        String time1 = begintimeList.get(i);
        String time2 = endingtimeList.get(i);
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        Date date1 = format.parse(time1);
        Date date2 = format.parse(time2);
        
        // 计算时间差的一半,得到中间时间并输出
        long halfDiff = (date2.getTime() - date1.getTime()) / 2;
        Date middleTime = new Date(date1.getTime() + halfDiff);
        System.out.println("中间时间: " + format.format(middleTime));
        
        // 将开始/结束时间转换为当天的总分钟数,方便计算总和
        Calendar startCal = Calendar.getInstance();
        startCal.setTime(date1);
        int startTotalMinutes = startCal.get(Calendar.HOUR_OF_DAY) * 60 + startCal.get(Calendar.MINUTE);
        
        Calendar endCal = Calendar.getInstance();
        endCal.setTime(date2);
        int endTotalMinutes = endCal.get(Calendar.HOUR_OF_DAY) * 60 + endCal.get(Calendar.MINUTE);
        
        // 核心判断逻辑:总和超过18:00(1080分钟)则视为夜间
        if (startTotalMinutes + endTotalMinutes > 1080) {
            System.out.println("当前时段视为夜间");
        } else {
            System.out.println("当前时段视为日间");
        }
        
    } catch (Exception e) {
        e.printStackTrace(); // 这里建议不要用空catch,打印异常能帮你快速排查时间解析问题
    }
}

几个关键点说明:

  • 用Calendar来提取时间的小时和分钟数,转换成总分钟数后计算总和,比直接拼接字符串对比要更可靠,也避免了时间格式的坑。
  • 你的例子里4:00(240分钟)+9:00(540分钟)=780分钟,小于1080,会判定为日间,完全符合预期。
  • 另外提个小建议:空的catch块会让你看不到时间解析失败的原因,加上e.printStackTrace()能帮你快速定位问题,比如输入的时间格式不对之类的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:52:32