Technical Article

Calculate Weekdays Between 2 Dates (revised)

,

This is a function that takes a start date and end date as parameters and returns the number of weekdays (Monday to Friday) in between. This function assumes that Sunday is set as the first day of the week. Adapted from a vb function that I wrote to calculate standard salary costs for billing purposes.
This version corrects a rounding error that may occur if a time is included with the parameters passed in.

--By Rick Carisse
CREATE FUNCTION [dbo].[fnGetWeekDays] 
(
@Start datetime,
@End datetime
)
RETURNS int 

AS  

BEGIN 

declare @DayCount int
declare @StartDate int
declare @EndDate int
--The offset value is needed because the function is 1 based for the first day ever whereas Sql is 0 based
--Also Sql 2000 fails to recognize that 1900 was a leap year and returns an error if Feb 29 1900 is used
--36526 is the date value of January 01, 2000 per VB and this function is derived from  my VB version
declare @Offset int  
set @Offset = 36526 - cast(cast('2000-01-01' as datetime) as int)

--Remove any time portion so day doesn't get rounded up
set @Start = cast(convert(varchar(10), @Start, 20) as datetime)
set @End = cast(convert(varchar(10), @End, 20) as datetime)

set @StartDate = cast(@Start as int)  + @Offset
set @EndDate = cast(@End as int) + @Offset

set @DayCount = round((((@EndDate + 1) - @StartDate) / 7), 0, 1) * 5

If ((@EndDate + 1) - @StartDate) % 7 <> 0 
begin
    If (@StartDate % 7) <= (@EndDate % 7)
    begin
      If (@StartDate % 7) = 0 
      begin
        If ((@EndDate + 1) - @StartDate) % 7 <> 1
        begin 
          set @DayCount = (select @DayCount + ((((@EndDate + 1) - @StartDate) % 7) - 2))
        End 
      end
      Else
      begin
        If (@StartDate % 7) = 1 
        begin
          set @DayCount = (select @DayCount + ((((@EndDate + 1) - @StartDate) % 7) - 1))
        end 
        Else
        begin
          set @DayCount = (select @DayCount + (((@EndDate + 1) - @StartDate) % 7))
        end
      End
    end
    Else
    begin
      If (@EndDate % 7) = 0 
      begin
        set @DayCount = (select @DayCount + ((((@EndDate + 1) - @StartDate) % 7) - 1))
      end
      Else
      begin 
        set @DayCount = (select @DayCount + ((((@EndDate + 1) - @StartDate) % 7) - 2))
      end
    End
End

return @DayCount

END

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating