How to count the number of workdays between two dates-C#

Recently In my project requirement was to show the number of workdays between two dates but exclude holidays and weekends. After a lot of research, I was able to manage in C# wihtout using any library. Check out the following code snippet

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime dt1 = new DateTime(1994, 12, 12, 12, 11, 33); // Start date Dec 12th
            DateTime dt2 = new DateTime(1994, 12, 31, 13, 56, 11); // End date Dec 31st
            List<DateTime> holidays = new List<DateTime>();
            holidays.Add(new DateTime(1994, 12, 14)); // Make Dec 14th a holiday
            Console.WriteLine(dt1.Date.ToShortDateString());
            Console.WriteLine(GetWorkingDays(dt1, dt2).ToString()); // without holidays
            Console.WriteLine(GetWorkingDays(dt1, dt2, holidays).ToString()); // with holidays
            Console.ReadLine();
        }

        //These crude methods assumes that DateTime b is later than DateTime a
        //If not they will just quit out and return 0
        public static int GetWorkingDays(DateTime a, DateTime b)
        {
            return GetWorkingDays(a, b, new List<DateTime>());
        }
        public static int GetWorkingDays(DateTime a, DateTime b, List<DateTime> holidays)
        {
            if (a > b) return 0;
            int c = 0;
            while (a.Date.ToShortDateString() != b.Date.ToShortDateString())
            {
                a = a.AddDays(1);
                if (!(a.DayOfWeek == DayOfWeek.Saturday || a.DayOfWeek == DayOfWeek.Sunday))
                {
                    bool isNotHoliday = true;
                    foreach (DateTime d in holidays)
                    {
                        if (d.ToShortDateString() == a.ToShortDateString())
                            isNotHoliday = false;
                    }
                    if (isNotHoliday)
                        c++;
                }
            }
            return c;
        }
    }
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru