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

后端 未结 14 1363
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:24

    Most of the answer I've found online didn't work as expected, so I tweaked an example on this thread, How to get current date and add five working days in Java. The code below appears to work better.

    public static Date addWorkingDays(Date date, int days) {
        if (days > 0) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
    
            int daysAdded = 0;
            do {
                cal.add(Calendar.DATE, 1);
                if (isWorkingDay(cal)) {
                    daysAdded++;
                }
            } while (daysAdded < days);
    
            return cal.getTime();;
        } else {
            return date;
        }
    }
    
    
     private static boolean isWorkingDay(Calendar cal) {
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY)
            return false;
        // tests for other holidays here        
        return true;
     }
    

提交回复
热议问题