How to add Business hours to Date considering not adding weekends ? - Java

前端 未结 7 948
盖世英雄少女心
盖世英雄少女心 2020-12-12 04:47

I want to add certain number of hours to date, ignoring the weekends

For example,

(Friday 18:00) + 48 = (Tuseday 18:00) (Saturday and Sunday are ignored)

7条回答
  •  执笔经年
    2020-12-12 05:33

    Please refer the below code, see if that helps you.

    public static Date getTaskEndTime(Date startDate, int hours) {
        // calculate the end time by adding the hours ignoring the weekends
        Calendar endCal = Calendar.getInstance();
        endCal.setTime(startDate);
    
        for (int i = 0; i < hours; hours = hours - 8) {
            if (!(endCal.get(Calendar.DAY_OF_WEEK) == 1 || endCal.get(Calendar.DAY_OF_WEEK) == 7)) {
                endCal.add(Calendar.DAY_OF_MONTH, 1);
            } else {
                endCal.add(Calendar.DAY_OF_MONTH, 1);
                hours = hours + 8;
            }
        }
        return endCal.getTime();
    }
    

提交回复
热议问题