Java - 计算除节假日(周六和周日)之外的天数

标签 java date dayofweek

我需要计算除节假日(周六和周日)之外的天数。例如我的开始日期是07/02/2018结束日期是15/02/2018 (采用 dd/MM/yyyy 格式)。我需要计算它们之间的工作日数。有人可以帮我吗?这是我的代码:

SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");

//Date date12 = dateformat3.parse("17/07/1989");
String date1 = "11/07/2018";
String date2 = "20/07/2018";

// Date date2 = dateformat3.parse("15/10/2007");
Calendar startdate = Calendar.getInstance();
startdate.setTime(dateformat3.parse(date1));
Calendar enddate = Calendar.getInstance();
enddate.setTime(dateformat3.parse(date2));
while (!startdate.after(enddate)) {
    int day = startdate.get(Calendar.DAY_OF_WEEK);
    if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
        workingDays++;
    }
}

我已尝试使用此代码,但没有显示任何结果。

最佳答案

你已经很接近了,只需要在 while 循环内增加开始日期。

public static void main(String[] args) throws Exception {
    System.out.println(countDays("07/02/2018", "15/02/2018"));
}

public static int countDays(String startDate, String endDate) throws Exception {
    int workingDays = 0;

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    Calendar startdate = Calendar.getInstance();
    startdate.setTime(sdf.parse(startDate));
    Calendar enddate = Calendar.getInstance();
    enddate.setTime(sdf.parse(endDate));

    while (!startdate.after(enddate)) {
        int day = startdate.get(Calendar.DAY_OF_WEEK);
        System.out.println(day);
        if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
            workingDays++;
        }

        // increment start date, otherwise while will give infinite loop
        startdate.add(Calendar.DATE, 1);
    }

    return workingDays;
}

如您所见,我从您那里提供的代码的唯一区别(除了删除硬编码值)是 startdate.add(Calendar.DATE, 1);

关于Java - 计算除节假日(周六和周日)之外的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49133264/

相关文章:

java - JApplet 不停止或不响应键盘输入

Linux根据输入日期复制文件

r - 如何在 R 中转换 Redis 日期

postgresql - 从 PostgreSQL 中的时间间隔获取特定星期几(周末)的数量

java - 为什么我在 JavaFX 上收到 java.lang.IllegalStateException "Not on FX application thread"?

java - Java中的匿名类和闭包有什么区别?

mysql - 如何比较sql数据库的日期和时间字段与当前日期,其中日期和时间是2019年6月6日11 :19AM this format in MYSQL

mysql 选择当前时间旁边的记录

c# - 系统.MissingMethodException : Method not found: 'System.String .get_DayName()'

java - 我怎样才能将其更改为数组?