Calculate Business Days

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?
CaliguianAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

SRigneyCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
eternal_21Commented:
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
CaliguianAuthor Commented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.