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

Java排除周末的日期差值计算实现方法求助

实现方案

核心逻辑为抽取出公共的排除周末的时间差计算方法,三个业务方法直接调用该方法的结果即可,避免重复编码。


第一步:新增公共计算工具方法

private static long calculateWorkTimeDiff(Date d1, Date d2) {
    // 统一日期顺序,保证start早于end,返回结果恒为正数
    Date start = d1.before(d2) ? d1 : d2;
    Date end = d1.before(d2) ? d2 : d1;
    Calendar cal = Calendar.getInstance();
    long workMilliseconds = 0;

    // 处理起始日的剩余时长
    cal.setTime(start);
    int startDayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
    if (startDayOfWeek != Calendar.SATURDAY && startDayOfWeek != Calendar.SUNDAY) {
        // 起始日为工作日,计算从start到当日23:59:59.999的时长
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 999);
        long startDayEnd = cal.getTimeInMillis();
        workMilliseconds += Math.min(startDayEnd, end.getTime()) - start.getTime();
    }

    // 日历移动到下一日0点
    cal.add(Calendar.DAY_OF_MONTH, 1);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    // 遍历处理中间所有日期
    while (cal.getTimeInMillis() < end.getTime()) {
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        // 跳过周六周日
        if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
            cal.add(Calendar.DAY_OF_MONTH, 1);
            continue;
        }
        // 计算当日结束时间
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 999);
        long currentDayEnd = cal.getTimeInMillis();
        if (currentDayEnd < end.getTime()) {
            // 完整工作日,加全天毫秒数
            workMilliseconds += 24 * 60 * 60 * 1000;
        } else {
            // 结束日所在的非完整工作日,加从0点到end的时长
            workMilliseconds += end.getTime() - (currentDayEnd - 24 * 60 * 60 * 1000 + 1);
        }
        // 移动到下一日0点
        cal.add(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
    }
    return workMilliseconds;
}

第二步:修改原有三个业务方法

仅需要将原有d2.getTime() - d1.getTime()替换为调用上述公共方法即可,其余逻辑无需改动:

修改后的getDatesDiff方法

public static String getDatesDiff(String date1, String date2) {
    String timeDiff = "";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date d1 = null;
    Date d2 = null;

    try {
        d1 = format.parse(date1);
        d2 = format.parse(date2);
        // 替换原有差值计算逻辑
        long diff = calculateWorkTimeDiff(d1, d2);
        timeDiff = "" + diff;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return timeDiff;
}

修改后的getDatesDiffAsDays方法

public static String getDatesDiffAsDays(String date1, String date2) {
    String timeDiff = "";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date d1 = null;
    Date d2 = null;

    try {
        d1 = format.parse(date1);
        d2 = format.parse(date2);
        // 替换原有差值计算逻辑
        long diff = calculateWorkTimeDiff(d1, d2);
        String days = "" + (diff / (24 * 60 * 60 * 1000));
            
        timeDiff = days;
        timeDiff = timeDiff.replaceAll("-", "");
        timeDiff = timeDiff + " days";
            
    } catch (Exception e) {
        e.printStackTrace();
    }
    return timeDiff;
}

修改后的getDatesDiffAsDate方法

public static String getDatesDiffAsDate(String date1, String date2) {
    String timeDiff = "";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date d1 = null;
    Date d2 = null;

    try {
        d1 = format.parse(date1);
        d2 = format.parse(date2);
        // 替换原有差值计算逻辑
        long diff = calculateWorkTimeDiff(d1, d2);
        String days = (diff / (24 * 60 * 60 * 1000)) + " days";
        String hours = (diff / (60 * 60 * 1000) % 24) + "h";
        String minutes = (diff / 1000 % 60) + "mts";
        String seconds = (diff / (60 * 1000) % 60) + "sec";
    
        timeDiff = days;
        timeDiff = timeDiff.replaceAll("-", "");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return timeDiff;
}

补充说明

  • 代码默认周六、周日为周末,如果你所在地区的周末规则不同,可修改Calendar.DAY_OF_WEEK的判断条件
  • 旧版SimpleDateFormat为线程不安全类,不建议定义为静态公共变量在多线程场景下使用,如果你使用的是Java 8及以上版本,更推荐用LocalDateTime、DateTimeFormatter等新时间API,线程安全且调用更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 11:18:03