Member_2_1242703
asked on
ASP.NET(C#) Eliminating weekends from a date range
I have two dates (sd, ed) that are essentially a range sd=startdate, ed=enddate
I want to iterate through each day of the range and sort of eliminate the weekends. Basically I want to take the start date and go through each day until I hit a Saturday, then "do something" then start over again until I hit the next Saturday and "do something" again and repeat until the end date is reached.
The code below shows how I'm currently going through each day in the range. I'm kind of stuck after that. Not sure what's the best practice here. I'm open to change this code or the logic.
I want to iterate through each day of the range and sort of eliminate the weekends. Basically I want to take the start date and go through each day until I hit a Saturday, then "do something" then start over again until I hit the next Saturday and "do something" again and repeat until the end date is reached.
The code below shows how I'm currently going through each day in the range. I'm kind of stuck after that. Not sure what's the best practice here. I'm open to change this code or the logic.
DateTime start = Convert.ToDateTime(sd);
DateTime end = Convert.ToDateTime(ed);
foreach (var day in start.EachDay(end))
{
//nested loop, if/then???
}
public static IEnumerable EachDay(this DateTime start, DateTime end)
{
DateTime currentDay = new DateTime(start.Year, start.Month, start.Day);
while (currentDay <= end)
{
yield return currentDay;
currentDay = currentDay.AddDays(1);
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
DateTime end = Convert.ToDateTime(ed);
for(var day = start.Date; start.Date <= end.Date; day = day.AddDays(1))
{
int day = (int)day.DayOfWeek; //Satureday = 6, Sunday=0
if(day!=6)
{
//doSomething();
}
}