简体   繁体   中英

How to add a number of days to a Date while skipping weekends and other holidays and start day is weekend or holiday

Below code calculates the number of workdays to be added and if the end date falls on holidays/weekends, shift the date to the next day.
But this code is on an assumption that the start date is not on weekends/holidays.

I want the code which also works if the start date falls on a weekend/holiday.

Please note this code was posted by ElenaSofea on 17 Jun'13 but as I was not able to comment on it asking this as a new question.
Reference: How to add a number of days to a Date while skipping weekends and other holidays

static DateTime CalculateFutureDate(DateTime fromDate, int numberofWorkDays,   
                                ICollection<DateTime> holidays)
{
    var futureDate = fromDate;
    for (var i = 0; i < numberofWorkDays; i++ )
    {
        if (futureDate.DayOfWeek == DayOfWeek.Saturday 
         || futureDate.DayOfWeek == DayOfWeek.Sunday
         || (holidays != null && holidays.Contains(futureDate)))
        {
            futureDate = futureDate.AddDays(1);
            numberofWorkDays++;
        }
        else
        {
            futureDate = futureDate.AddDays(1);
        }
    }
    while(futureDate.DayOfWeek == DayOfWeek.Saturday 
         || futureDate.DayOfWeek == DayOfWeek.Sunday
         || (holidays != null && holidays.Contains(futureDate)))
    {
        futureDate = futureDate.AddDays(1);
    }
    return futureDate;
}

Try to pass the date as input, such that this method validates to check whether it is saturday or sunday

public static boolean isValidateSundayorSaturday(String date) throws Exception {

        Calendar calendar = Calendar.getInstance();     
        if (date != null) {

            calendar.setTime(getDate(date,null));
            int day = calendar.get(Calendar.DAY_OF_WEEK);

            if (day == Calendar.SUNDAY || day == Calendar.SATURDAY) {
                return true;
            } 
        }
        return false;
    }

You've to provide all excluded dates because it is different from region to region even in same country.

If you want to see code here you go

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM