Go4Expert

Go4Expert (http://www.go4expert.com/)
-   ASP (http://www.go4expert.com/articles/asp-tutorials/)
-   -   Calculate Next Business Date Given Start Date And No. Of Days (http://www.go4expert.com/articles/calculate-business-date-start-date-days-t19103/)

naimish 20Aug2009 15:40

Calculate Next Business Date Given Start Date And No. Of Days
 

Introduction



This stored procedure (works same in vb, c#) adds the given number of Business days to the given date. Only business days aare taken into account. Saturday and Sunday are not included.

Background



Find out how many weekends will come between start and end date and add that many extra days to the no. of days to the start date.

(2 days for one weekend)
  1. Say you have to add 'N' business days days to start date ('stdate')
  2. Find out Working days left is a week call it 'wkdays'. (For ex if 'stdate' is tuesdays, then working days left = 3)
  3. Now we need to calculate how many weeks will come in between. This is done with a formula

    The formula is simple. weeks = ( N - 'wkdays' + 4) / 5

    First we subtract the days which are left in a week. ( N - wkdays). Now we are left with the no of days added.

    For this we add 4 to left days to take current week into account and then divide by 5 to see how many weekends will come as our week has only 5 business days.
  4. once we have no. of weekends in between we can simply calculate total no. of days ('tdays') to be added.

    tdays = N + (weeks*2)
  5. Once we have tdays we can add these n weeksends are taken into account automatically.

P.S This code uses 2 fucntions
  1. DatePart - to calulate day of week
  2. DateAdd - to add the tdays in start date to get end date.

The code



Code:

Create procedure SpAddBusinessDays1 (@dtStartDate datetime, @intadddays int)
as
begin
    declare
    @intwkday int  --store day of week
        ,@intweeks int  --how many weeks in between
    ,@dtEndDate datetime  --To store end date
 
        if datepart(dw, @dtStartDate)= 7  --Converting saturday to sunday
                select @dtStartDate = dateadd(d, 1, @dtStartDate)
       
        select @intwkday = 6 - datepart(dw, @dtStartDate)  --working days left in week
        select @intweeks = (@intadddays - @intwkday + 4) / 5  --No of weeks
        select @intadddays = (@intadddays + (@intweeks * 2))  --total days to add
        select @dtEndDate = dateadd(d, @intadddays, @dtStartDate)  -- end date
       
        print @dtEndDate
end
---


Saket 26Aug2009 13:51

Re: Calculate Next Business Date Given Start Date And No. Of Days
 
Nice work mr. naimish

shabbir 2Sep2009 18:56

Re: Calculate Next Business Date Given Start Date And No. Of Days
 
Nomination for Article of the month - Aug 2009 Started.


All times are GMT +5.5. The time now is 14:23.