.Net - find business days

Goal:

Find the business days; i.e. exclude weekends

How to:

Here is some code to get the first business day after or before the weekend. It is surprisingly simple but thought the code may help save folks some time. Just a note that there is no built-in .Net feature to give you public US or other holiday calendar dates, you need to build your own using a table to keep track of public holidays in most situations. Simple enough to do, extend the methods below to query a database or xml or JSON, etc, file with your company or country holiday calendar.

 

    public static class DayOfWeekUtility
    {
        public static DateTime GetFirstBusinessDayAfter(DateTime baseDate)
        {
            var businessDate = baseDate;
            var dayOfWeek = businessDate.DayOfWeek;
           
            if (dayOfWeek == DayOfWeek.Saturday || dayOfWeek == DayOfWeek.Sunday)
            {
                if (dayOfWeek == DayOfWeek.Saturday)
                    businessDate = businessDate.AddDays(2);
                if (dayOfWeek == DayOfWeek.Sunday)
                    businessDate = businessDate.AddDays(1);
            }
            return businessDate;
        }

        public static DateTime GetFirstBusinessDayBefore(DateTime baseDate)
        {
            var businessDate = baseDate;
            var dayOfWeek = businessDate.DayOfWeek;

            if (dayOfWeek == DayOfWeek.Saturday || dayOfWeek == DayOfWeek.Sunday)
            {
                if (dayOfWeek == DayOfWeek.Saturday)
                    businessDate = businessDate.AddDays(-1);
                if (dayOfWeek == DayOfWeek.Sunday)
                    businessDate = businessDate.AddDays(-2);
            }
            return businessDate;
        }

    }

 

 

Print | posted @ Tuesday, October 11, 2011 12:51 PM

Comments on this entry:

Gravatar # re: .Net - find business days
by Anaheim Boot Camp at 10/14/2011 10:23 AM

But these types of the code will be understandable for the professional people who are highly strong background of the engineering.
Post A Comment
Title:
Name:
Email:
Comment:
Verification: