What\'s the easiest way to compute the amount of working days since a date? VB.NET preferred, but C# is okay.
And by \"working days\", I mean all days excluding Satu
DateDiff along with a few other Date* functions are unique to VB.NET and often the subject of envy from C# developers. Not sure it'll be very helpful in this case, though.
We combined two CodeProject articles to arrive at a complete solution. Our library is not concise enough to post as source code, but I can point you to the two projects we used to achieve what we needed. As always with CodeProject articles, read the comments, there may be important info in them.
Calculating business days:http://www.codeproject.com/KB/cs/busdatescalculation.aspx
An alternative business day calc: http://www.codeproject.com/KB/cs/datetimelib.aspx
Calculating Holidays:http://www.codeproject.com/KB/dotnet/HolidayCalculator.aspx
This'll do what you want it to. It should be easy enough to convert to VB.NET, it's been too long for me to be able to do it though.
DateTime start = DateTime.Now;
DateTime end = start.AddDays(9);
IEnumerable<DateTime> holidays = new DateTime[0];
// basic data
int days = (int)(end - start).TotalDays;
int weeks = days / 7;
// check for a weekend in a partial week from start.
if (7- (days % 7) <= (int)start.DayOfWeek)
days--;
if (7- (days % 7) <= (int)start.DayOfWeek)
days--;
// lose the weekends
days -= weeks * 2;
foreach (DateTime dt in holidays)
{
if (dt > start && dt < end)
days--;
}
The easiest way is probably something like
DateTime start = new DateTime(2008, 10, 3);
DateTime end = new DateTime(2008, 12, 31);
int workingDays = 0;
while( start < end ) {
if( start.DayOfWeek != DayOfWeek.Saturday
&& start.DayOfWeek != DayOfWeek.Sunday ) {
workingDays++;
}
start = start.AddDays(1);
}
It may not be the most efficient but it does allow for the easy checking of a list of holidays.
in general (no code) -
fiddle with the start/end dates so that they fall monday to monday, then add back the difference
[apologies for the no-code generalities, it's late]
[c.f. endDate.Subtract(startDate).TotalDays]
Here is a sample of Steve's formula in VB without the holiday subtraction:
Function CalcBusinessDays(ByVal DStart As Date, ByVal DEnd As Date) As Decimal
Dim Days As Decimal = DateDiff(DateInterval.Day, DStart, DEnd)
Dim Weeks As Integer = Days / 7
Dim BusinessDays As Decimal = Days - (Weeks * 2)
Return BusinessDays
Days = Nothing
Weeks = Nothing
BusinessDays = Nothing
End Function