Skip to content

Instantly share code, notes, and snippets.

@ststeiger
Created July 1, 2015 15:19
Show Gist options
  • Save ststeiger/ca2d2d35953e8472701a to your computer and use it in GitHub Desktop.
Save ststeiger/ca2d2d35953e8472701a to your computer and use it in GitHub Desktop.
Get the end of an ISO week from a date
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fu_get_ISOWeekEnd]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fu_get_ISOWeekEnd]
GO
-- PRE: Valid year and week no#
-- POST: Last day of ISO week no#
CREATE FUNCTION [dbo].[fu_get_ISOWeekEnd](@year int, @ISO_WEEK int)
RETURNS datetime
AS
BEGIN
DECLARE @FirstISOweekOfYearDay datetime
DECLARE @WeekEnd datetime
SELECT @FirstISOweekOfYearDay = CAST(CAST(@year AS char(4)) AS datetime)
SELECT @FirstISOweekOfYearDay = DATEADD(ww, DATEDIFF(ww, 0, @FirstISOweekOfYearDay), 0)
IF DATEPART(isowk, @FirstISOweekOfYearDay) > 1
SET @FirstISOweekOfYearDay = @FirstISOweekOfYearDay + 7
SET @WeekEnd = DATEADD(dd, @ISO_WEEK * 7 - 1, @FirstISOweekOfYearDay)
RETURN @WeekEnd
END
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment