I am trying to calculate the weekend days between two entered dates using the following code:
public int CalcularDias(DateTime fecha, DateTime fin)
{
int contador = 0;
DateTime dtInicio = fecha;
DateTime dtFin = fin;
for (int k = dtInicio.Day; k < dtFin.Day;k++)
{
while (dtInicio.DayOfWeek == DayOfWeek.Saturday || dtInicio.DayOfWeek == DayOfWeek.Sunday)
{
dtInicio = dtInicio.AddDays(1);
contador++;
}
dtInicio = dtInicio.AddDays(1);
}
return contador;
}
The problem I have is that when the day of the date is greater than the date to compare it gives me a calculation error and I am trying to solve this error
A for is used for more than going through integers, you can perfectly do a for of datetimes and go through the days.
The while you have I don't understand why you put it, I think it doesn't make sense, it should be an if
Maybe you could try something like this:
What I do is add one day if it's Sunday and two days if it's Saturday, also if it's during the week only one day is added.