Technical Article

Difference between two dates in weeks

,

The sripts creates a scalar function which accepts start date and end date as the paramteres and returns diffrerence between them in weeks. It takes into account @@DATEFIRST setting and assumes start date is earlier then end date.

CREATE FUNCTION [dbo].[WeekDiff]
(
@StartDate DateTime,
@EndDate DateTime
)
RETURNS int
AS
BEGIN
DECLARE @StartDayOfStartWeek datetime;
DECLARE @StartDayOfEndWeek datetime;

SELECT @StartDayOfStartWeek = DATEADD(d, -DATEPART(dw, @StartDate) + 1, @StartDate);
SELECT @StartDayOfEndWeek = DATEADD(d, -DATEPART(dw, @EndDate) + 1, @EndDate);
RETURN DATEDIFF(d, @StartDayOfStartWeek, @StartDayOfEndWeek)/7;
END

Rate

2.25 (4)

You rated this post out of 5. Change rating

Share

Share

Rate

2.25 (4)

You rated this post out of 5. Change rating