Solved

# Calculate Business Days

Posted on 2004-11-29
1,155 Views
Last Modified: 2008-02-01
I am trying to figure out what a certain date was xx amount of business days ago (business days meaning monday - friday).  For instance, today is November 29th, 2004... 5 business days ago was November 22nd, 2004 (don't need to worry about holidays).  I need to be able to calculate that on the fly.  Any suggestions?
0
Question by:Caliguian
3 Comments

LVL 15

Accepted Solution

If you are not worried about the holidays then it's not too difficult.

DateTime dtstart = DateTime.Parse("11/29/2004");
int xBusinessDays = 5;
DateTime dtxDaysAgo = DateTime.Today;
int i = 0;
// use >= 0 to ignore today, if you want to count today as a business day then use > 0.
while( xBusinessDays >= 0 )
{
dtxDaysAgo = dtstart.AddDays(i);
if( dtxDaysAgo.DayOfWeek == System.DayOfWeek.Sunday
|| dtxDaysAgo.DayOfWeek == System.DayOfWeek.Saturday )
{
// Don't count Sunday and Saturday.
}
else
{
xBusinessDays--;
}
i--;
}

// Now dtxDaysAgo holds the answer
Console.WriteLine(dtxDaysAgo);
0

LVL 10

Assisted Solution

You could use this to go forward and backwards as well:

static DateTime AddBusinessDays(DateTime date, int businessDays)
{
for(int i = 0; i < (businessDays < 0 ? -businessDays : businessDays);)
{
date = date.AddDays(businessDays < 0 ? -1 : 1);
switch(date.DayOfWeek)
{
case DayOfWeek.Monday:
case DayOfWeek.Tuesday:
case DayOfWeek.Wednesday:
case DayOfWeek.Thursday:
case DayOfWeek.Friday:
{
i++;
break;
}
default:
{
break;
}
}
}

return date;
}
0

Author Comment

Both of your answer do what i want.  I gave more points to the first answer just for the reason that it was first. Thanks for your help.
0

## Write Comment

Please enter a first name

Please enter a last name

We will never share this with anyone.

## Featured Post

### Suggested Solutions

Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
how to add IIS SMTP to handle application/Scanner relays into office 365.
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

#### 759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

#### Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!