Kwasi Denkyira

Kwasi Denkyira

  • 1.4k
  • 192
  • 13.4k

Get Weekly Business dates for a given two dates range

Feb 21 2019 8:32 PM
I want to generate weekly business dates between two dates excluding weekends and holidays. So I want a results
 
week 1
StartDate {2/18/2019 12:00:00 AM}
EndDate{2/25/2019 12:00:00 AM---wrong end date} ---> 2/27/2019 correct end date
 
week 2
StartDate {2/25/2019 12:00:00 AM}
EndDate{3/4/2019 12:00:00 AM--wrong end date}----->3/6/2019 -- correct end date
 
Below is my code. Any help will be appreciated
  1. class Program    
  2.     {    
  3.         public class WeekStartEnd    
  4.         {    
  5.             public DateTime firstDate;    
  6.             public DateTime SecondDate;    
  7.         }
  8.         static void Main(string[] args)    
  9.         {    
  10.             //usage:    
  11.             DateTime StartDate = DateTime.Parse("02/12/2019");             
  12.             DateTime SeriesEndDate = DateTime.Parse("12/31/2025");    
  13.              
  14.             DateTime firstMonday = Enumerable.Range(1, (SeriesEndDate - StartDate).Days +1)    
  15.                 .SkipWhile(x => StartDate.AddDays(x).DayOfWeek != DayOfWeek.Monday)    
  16.                 .Select(x => StartDate.AddDays(x))    
  17.                 .First();    
  18.          
  19.             TimeSpan ts = (TimeSpan)(SeriesEndDate - firstMonday);    
  20.              
  21.             List<WeekStartEnd> dates = new List<WeekStartEnd>();    
  22.          
  23.             for (int i = 0; i < ts.Days; i += 7)    
  24.             {    
  25.                      
  26.                 dates.Add(new WeekStartEnd() { firstDate = firstMonday.AddDays(i), SecondDate = firstMonday.AddDays(i + 7) });    
  27.             }    
  28.     
  29.     
  30.             Console.WriteLine(dates);    
  31.     
  32.             }    
  33.         }    
  34.     }    

Answers (4)