Kwasi Denkyira

Kwasi Denkyira

  • 1.5k
  • 197
  • 14.8k

I want to generate a list of weekly business dates

Feb 22 2019 1:44 PM
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.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. namespace SeriesTest  
  5. {  
  6. class Program  
  7. {  
  8. public class BusinessWeekDays  
  9. {  
  10. public DateTime Monday;  
  11. public DateTime Sunday;  
  12. }  
  13. private static List Holidays = new List()  
  14. {  
  15. new DateTime(1, 1, 1), //New Year Day  
  16. new DateTime(1, 5, 1), //Labour Day  
  17. new DateTime(1, 7, 4), //Independence Day  
  18. new DateTime(1, 3, 1), //Martin Luther King Jr. Day  
  19. new DateTime(1, 3, 2), //Presidents Day  
  20. new DateTime(1, 12, 25), //Christmas  
  21. new DateTime(1, 5, 5), //Memorial Day  
  22. new DateTime(1, 9, 1), //Labor Day  
  23. new DateTime(1, 10, 2), //Columbus Day  
  24. new DateTime(1, 11, 4), //Columbus Day  
  25. };  
  26. private static bool IsHoliday(DateTime value, List holidays = null)  
  27. {  
  28. if (null == holidays)  
  29. holidays = Holidays;  
  30. return (value.DayOfWeek == DayOfWeek.Sunday) ||  
  31. (value.DayOfWeek == DayOfWeek.Saturday) ||  
  32. holidays.Any(holiday => holiday.Day == value.Day &&  
  33. holiday.Month == value.Month);  
  34. }  
  35. public static int BusinessDays(DateTime fromDate, DateTime toDate, List holidays = null)  
  36. {  
  37. int result = 0;  
  38. for (var date = fromDate;  
  39. date < toDate.Date;  
  40. date = date.AddDays(1))  
  41. if (!IsHoliday(date, holidays))  
  42. result += 1;  
  43. return result;  
  44. }  
  45. static void Main(string[] args)  
  46. {  
  47. var StartDate = DateTime.Parse("02/12/2019");  
  48. var SeriesEndDate = DateTime.Parse("12/31/2025");  
  49. var holidays = new List();  
  50. var firstMonday = Enumerable.Range(0, 7)  
  51. .SkipWhile(x => StartDate.AddDays(x).DayOfWeek != DayOfWeek.Monday)  
  52. .Select(x => StartDate.AddDays(x))  
  53. .First();  
  54. var ts = (SeriesEndDate - firstMonday);  
  55. var dates = new List();  
  56. for (var i = 0; i < ts.Days; i += 7)  
  57. {  
  58. //Remove holidays. Weekend already removed here  
  59. if (BusinessDays(StartDate, SeriesEndDate, holidays) != 0)  
  60. {  
  61. dates.Add(new BusinessWeekDays { Monday = firstMonday.AddDays(i), Sunday = firstMonday.AddDays(i + 9) });  
  62. }  
  63. }  
  64. Console.WriteLine(dates);  
  65. }  
  66. }  
  67. }

Answers (1)