I want to generate a list of weekly business dates between two dates excluding weekends and holidays. I have managed to exclude the Weekends and created a routine for the holidays. Now I need to exclude the holidays. Below is my code.
- using System;  
- using System.Collections.Generic;  
- using System.Linq;  
- namespace SeriesTest  
- {  
- class Program  
- {  
- public class BusinessWeekDays  
- {  
- public DateTime Monday;  
- public DateTime Sunday;  
- }  
- private static List Holidays = new List()  
- {  
- new DateTime(1, 1, 1),   
- new DateTime(1, 5, 1),   
- new DateTime(1, 7, 4),   
- new DateTime(1, 3, 1),   
- new DateTime(1, 3, 2),   
- new DateTime(1, 12, 25),   
- new DateTime(1, 5, 5),   
- new DateTime(1, 9, 1),   
- new DateTime(1, 10, 2),   
- new DateTime(1, 11, 4),   
- };  
- private static bool IsHoliday(DateTime value, List holidays = null)  
- {  
- if (null == holidays)  
- holidays = Holidays;  
- return (value.DayOfWeek == DayOfWeek.Sunday) ||  
- (value.DayOfWeek == DayOfWeek.Saturday) ||  
- holidays.Any(holiday => holiday.Day == value.Day &&  
- holiday.Month == value.Month);  
- }  
- public static int BusinessDays(DateTime fromDate, DateTime toDate, List holidays = null)  
- {  
- int result = 0;  
- for (var date = fromDate;  
- date < toDate.Date;  
- date = date.AddDays(1))  
- if (!IsHoliday(date, holidays))  
- result += 1;  
- return result;  
- }  
- static void Main(string[] args)  
- {  
- var StartDate = DateTime.Parse("02/12/2019");  
- var SeriesEndDate = DateTime.Parse("12/31/2025");  
- var holidays = new List();  
- var firstMonday = Enumerable.Range(0, 7)  
- .SkipWhile(x => StartDate.AddDays(x).DayOfWeek != DayOfWeek.Monday)  
- .Select(x => StartDate.AddDays(x))  
- .First();  
- var ts = (SeriesEndDate - firstMonday);  
- var dates = new List();  
- for (var i = 0; i < ts.Days; i += 7)  
- {  
-   
- if (BusinessDays(StartDate, SeriesEndDate, holidays) != 0)  
- {  
- dates.Add(new BusinessWeekDays { Monday = firstMonday.AddDays(i), Sunday = firstMonday.AddDays(i + 9) });  
- }  
- }  
- Console.WriteLine(dates);  
- }  
- }  
- }