Search

Monday, January 28, 2013

Get Start and End date of Fortnight

Sometime it is needed to get the start and end date of fortnight.
Use below query to get the result:


DECLARE @DateInput DATETIME
SET @DateInput = '28-Jan-2013'

DECLARE @FNStartDate DATETIME
DECLARE @FNEndDate DATETIME

IF DAY(@DateInput) < 16  -- First Half of Month
BEGIN
SET @FNStartDate = CAST(CAST(YEAR(@DateInput) AS VARCHAR(4)) + '/' + CAST(MONTH(@DateInput) AS VARCHAR(2)) + '/01' AS DATETIME)
SET @FNEndDate = CAST(CAST(YEAR(@DateInput) AS VARCHAR(4)) + '/' + CAST(MONTH(@DateInput) AS VARCHAR(2)) + '/15' AS DATETIME)
END
ELSE -- Second Half of Month
BEGIN
SET @FNStartDate = CAST(CAST(YEAR(@DateInput) AS VARCHAR(4)) + '/' + CAST(MONTH(@DateInput) AS VARCHAR(2)) + '/16' AS DATETIME)
SET @FNEndDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@DateInput)+1,0))
END

SELECT @FNStartDate AS 'StartDate', @FNEndDate AS 'EndDate'

No comments:

Post a Comment