Skip to content

Instantly share code, notes, and snippets.

@jerfowler
Last active December 14, 2015 14:19
Show Gist options
  • Save jerfowler/5099945 to your computer and use it in GitHub Desktop.
Save jerfowler/5099945 to your computer and use it in GitHub Desktop.
This is how I calculate First/Last day of any given month and prior year corresponding dates.
DECLARE
@Date DateTime,
@FirstDay DateTime,
@LastDay DateTime,
@PriorFirstDay DateTime,
@PriorLastDay DateTime
SET @Date='2/15/2013'
SELECT @FirstDay = CAST(MONTH(@Date) as varchar(2))+'/1/'+CAST(YEAR(@Date) as varchar(4))
SELECT @LastDay = DATEADD(day, -1, CAST(MONTH(DATEADD(month, 1, @Date)) as varchar(2))
+ '/1/' + CAST(YEAR(DATEADD(month, 1, @Date)) as varchar(4)))
SELECT @PriorFirstDay = DATEADD(year, -1, @FirstDay)
SELECT @PriorLastDay = DATEADD(day, -1, CAST(MONTH(DATEADD(month, 1, DATEADD(year, -1, @Date))) as varchar(2))
+ '/1/' + CAST(YEAR(DATEADD(month, 1, DATEADD(year, -1, @Date))) as varchar(4)))
SELECT @Date AS [Date],
@FirstDay AS [FirstDay],
@LastDay AS [LastDay],
@PriorFirstDay AS [PriorFirstDay],
@PriorLastDay AS [PriorLastDay]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment