计算包括节假日在内的工作日

计算包括节假日在内的工作日

本文介绍了计算包括节假日在内的工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算两个日期之间的工作日.例如:我们在 7 月 4 日放假(在美国).所以如果我的日期是日期 1 = 07/03/2012日期 2 = 07/06/2012

i need to calculate the business days between two dates.ex : we have holiday(in USA) on july4th. so if my dates aredate1 = 07/03/2012date2 = 07/06/2012

由于 7 月 4 日是假期,因此这些日期应该是 1 个工作日.

no of business days b/w these dates should be 1 since july4th is holiday.

我有一个下面的方法来计算工作日,它只计算周末而不是假期.还有什么方法可以计算假期....请帮助我.

i have a below method to calclulate the business days which will only counts week ends but not holidays.is there any way to calculate holidays also....please help me on this.

  public static int getWorkingDaysBetweenTwoDates(Date startDate, Date endDate) {
    Calendar startCal;
    Calendar endCal;
    startCal = Calendar.getInstance();
    startCal.setTime(startDate);
    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 {
        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());

    return workDays;
}

推荐答案

假设您有一个包含所有假期的列表,正如您所提到的.

Let's pretend you have a list containing all the holidays, as you mentioned.

ArrayList<Integer> holidays = ...

只需在 do-while 中为 if 条件添加一个条件:

Just add a condition to your if condition in your do-while:

do {
          startCal.add(Calendar.DAY_OF_MONTH, 1);
          if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY
          && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY
          && !holidays.contains((Integer) startCal.get(Calendar.DAY_OF_YEAR))) {
              ++workDays;
          }
} while (startCal.getTimeInMillis() < endCal.getTimeInMillis());

为简单起见,我假设 holiday 包含格式与 Calendar.DAY_OF_YEAR 相同的日期.

For simplicity's sake, I've assumed holiday contains dates in the format identical to Calendar.DAY_OF_YEAR.

这篇关于计算包括节假日在内的工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:19