计算Java中两个日期之间的工作日数 [英] Calculate number of weekdays between two dates in Java

查看:71
本文介绍了计算Java中两个日期之间的工作日数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我一些 Java 代码片段,我可以在其中获取两个日期之间的业务天数(周六和周日除外).

解决方案

public static int getWorkingDaysBetweenTwoDates(Date startDate, Date endDate) {日历 startCal = Calendar.getInstance();startCal.setTime(startDate);日历 endCal = Calendar.getInstance();endCal.setTime(endDate);int 工作日 = 0;//如果开始和结束相同返回0if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {返回0;}if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) {startCal.setTime(endDate);endCal.setTime(startDate);}做 {//不包括开始日期startCal.add(Calendar.DAY_OF_MONTH, 1);if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {++工作日;}} while (startCal.getTimeInMillis() < endCal.getTimeInMillis());//不包括结束日期返回工作日;}

<块引用>

开始日期和结束日期是唯一的,只有给定日期之间的天数日期将被计算在内.不包括开始日期和结束日期.

Can anyone point me to some Java snippet wherein i can get business (except Sat and Sun) days between two dates.

解决方案

public static int getWorkingDaysBetweenTwoDates(Date startDate, Date endDate) {
    Calendar startCal = Calendar.getInstance();
    startCal.setTime(startDate);        

    Calendar endCal = Calendar.getInstance();
    endCal.setTime(endDate);

    int workDays = 0;

    //Return 0 if start and end are the same
    if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {
        return 0;
    }

    if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) {
        startCal.setTime(endDate);
        endCal.setTime(startDate);
    }

    do {
       //excluding start date
        startCal.add(Calendar.DAY_OF_MONTH, 1);
        if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
            ++workDays;
        }
    } while (startCal.getTimeInMillis() < endCal.getTimeInMillis()); //excluding end date

    return workDays;
}

Start date and end date are exclusive, Only the days between given dates will be counted. Start date and end date will not be included.

这篇关于计算Java中两个日期之间的工作日数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆