[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1158
  • Last Modified:

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?
0
Caliguian
Asked:
Caliguian
2 Solutions
 
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
 
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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now