Skip to content
Advertisement

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

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)

since the company works 24 hours, business hours are 24. But still i could not get how to add hours only on business days

function can be something like:

public Date getTaskEndTime(Calendar startDate, int hours){
   // calculate the end time by adding the hours ignoring the weekends
}

Advertisement

Answer

Add hours in steps not bigger then 24hours. And check after each step if you end up on a saturday or sunday. In each case add another 24hours. That should do what you want.

public Date getTaskEndTime(Calendar startDate, int hours){
    while (hours > 0){
        int step = 0;
        if(hours > 24) step = 24;
        else step = hours;          
        hours -= step;          
        startDate.add(Calendar.HOUR_OF_DAY, step);          
        int dayOfWeek = startDate.get(Calendar.DAY_OF_WEEK);
        if(dayOfWeek == Calendar.SATURDAY) hours += 24;
        if(dayOfWeek == Calendar.SUNDAY) hours += 24;
    }
    return startDate.getTime();
}
Advertisement