Mar 4, 2012

Calculate business days in c# (with variable business days per week)

One of my past posts (i.e. here) I discussed calculating hire days in JavaScrips for equipments (including start and end days) with variable number of days per week. It could be 5 as a default, but one can work on Saturdays too and also there can be non-stop operations which we should count 7 days per week. Here is the appropriate c# code.

public static int getHireDays(DateTime startDate, DateTime endDate, int NoOfDays)
        {
        int _saturdays = 0;
        int _sundays = 0;
        int _Bdays = 0;

        endDate += TimeSpan.FromDays(1); //add one beacuse we need days INCLUDING end date
        long ticks = (endDate.Ticks - startDate.Ticks) / 10000000; //seconds
        int days = (int)(ticks / 86400);

        endDate -= TimeSpan.FromDays(1);
        for (DateTime i = startDate; i < endDate; i += TimeSpan.FromDays(1))
        {
            if (i.DayOfWeek == DayOfWeek.Saturday) { _saturdays = _saturdays + 1; }
            if (i.DayOfWeek == DayOfWeek.Sunday) { _sundays = _sundays + 1; }
        }

        switch (NoOfDays)
        {
            case 5:
                _Bdays = days - (_sundays + _saturdays);
                break;
            case 6:
                _Bdays = days - _saturdays;
                break;
            case 7:
                _Bdays = days;
                break;
        }
        return _Bdays;
        }

Since I am doing a loop here, this can be bit inappropriate for long periods, but I haven’t tested the performances for long periods.

No comments:

Post a Comment