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.
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)
- Say you have to add 'N' business days days to start date ('stdate')
- Find out Working days left is a week call it 'wkdays'. (For ex if 'stdate' is tuesdays, then working days left = 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.
- once we have no. of weekends in between we can simply calculate total no. of days ('tdays') to be added.
tdays = N + (weeks*2)
- Once we have tdays we can add these n weeksends are taken into account automatically.
P.S This code uses 2 fucntions
- DatePart - to calulate day of week
- DateAdd - to add the tdays in start date to get end date.
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 ---