How can I add business days to the current date in Java?

后端 未结 14 1408
Happy的楠姐
Happy的楠姐 2020-12-03 02:05

How can I add business days to the current date in Java?

public Calendar addBusinessDate(Calendar cal, int days) {
//
// code goes over here
//
}
         


        
14条回答
  •  孤街浪徒
    2020-12-03 02:48

    This algorithm calculates the next business date for a given date (business days are from monday to friday in my country), you can adapt it to iterate the number of days you need to add.

    public Calendar nextBusinessDate(Calendar cal) {
    
        List holidays = ********
        // Here get list of holidays from DB or some other service...
    
        GregorianCalendar calCp = new GregorianCalendar();
        calCp.setTime(cal.getTime());
        calCp.add(Calendar.DAY_OF_MONTH, 1);
    
        boolean isSaturday = (calCp.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY);
        boolean isSunday = (calCp.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY);
        boolean isHoliday = holidays.contains(calCp);
    
        while (isSaturday || isSunday || isHoliday) {
          if (isSaturday) {
              calCp.add(Calendar.DAY_OF_MONTH, +2); // is saturday, make it monday
            } else {
            if (isSunday) {
                calCp.add(Calendar.DAY_OF_MONTH, +1); // is sunday, make it monday
            } else {
                if (isHoliday) {
                     calCp.add(Calendar.DAY_OF_MONTH, +1); // is holiday, make it next day
                   }
                }
            }
          calCp = new GregorianCalendar();
          calCp.setTime(cal.getTime());
          isSaturday = (calCp.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY);
          isSunday = (calCp.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY);
        isHoliday = holidays.contains(calCp);
        } // end while
    
        return calCp;
    }
    

提交回复
热议问题