patterncsharpModerate
Find the number of working days between two dates inclusively
Viewed 0 times
numberthedatesworkingtwobetweenfindinclusivelydays
Problem
The objective is to find the number of working days (days spanning from Monday to Friday) between two given dates inclusively.
Is there the simpler or better way to do so? Any comment and suggestion is welcome.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
for (int i = 13; i = DayOfWeek.Monday && test <= DayOfWeek.Friday)
totalWorkingDays++;
}
return totalWorkingDays;
}
}
}Is there the simpler or better way to do so? Any comment and suggestion is welcome.
Solution
Personally, I think your approach is very complicated for what it should be trying to do: loop over all days between the start and the end date and count how many of those are not in the weekend.
Translating that sentence to code, gives me this:
I find this much easier to interpret than a bunch of modulos, casts and divisions.
Translating that sentence to code, gives me this:
private static int GetNumberOfWorkingDaysJeroen(DateTime start, DateTime stop)
{
int days = 0;
while(start <= stop)
{
if(start.DayOfWeek != DayOfWeek.Saturday && start.DayOfWeek != DayOfWeek.Sunday)
{
++days;
}
start = start.AddDays(1);
}
return days;
}I find this much easier to interpret than a bunch of modulos, casts and divisions.
Code Snippets
private static int GetNumberOfWorkingDaysJeroen(DateTime start, DateTime stop)
{
int days = 0;
while(start <= stop)
{
if(start.DayOfWeek != DayOfWeek.Saturday && start.DayOfWeek != DayOfWeek.Sunday)
{
++days;
}
start = start.AddDays(1);
}
return days;
}Context
StackExchange Code Review Q#66432, answer score: 17
Revisions (0)
No revisions yet.