Skip to content

Instantly share code, notes, and snippets.

@mikesigs
Created April 26, 2016 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikesigs/a6467623283c713920208583e44cc943 to your computer and use it in GitHub Desktop.
Save mikesigs/a6467623283c713920208583e44cc943 to your computer and use it in GitHub Desktop.
SQL Date Conversions
/* *** SQL Server Date Calculations *** */
-- First day of prior month
SELECT DATEADD(mm, DATEDIFF(mm,0,DATEADD(mm,-1-DATEPART(day,GetDate()),GetDate())),0) /*first day of prior month*/
-- Last month
SELECT CAST(DATEPART(m, GetDate())-1 AS INT) /*last month*/
-- Current year
SELECT CAST(DATEPART(yyyy, GetDate())AS INT) /*current year*/
-- Current day
SELECT CAST(DATEPART(dd, GetDate())AS INT) /*current day*/
-- First day of current year
SELECT DATEADD(yy, DATEDIFF(yy,0,GetDate()), 0) /* first day of current year*/
-- First day of current month
SELECT DATEADD(mm, DATEDIFF(mm,0,GetDate()), 0) /*first day of current month*/
-- Last day of prior month
SELECT DATEADD(ms,-3,DATEADD(mm, DATEDIFF(mm,0,GetDate() ), 0)) /*last day of prior month*/
-- First day of the quarter
SELECT DATEADD(qq, DATEDIFF(qq,0,GetDate()), 0) /*first day of the quarter*/
-- Midnight for current day
SELECT DATEADD(dd, DATEDIFF(dd,0,GetDate()), 0) /*midnight for current day*/
-- Last day of current month
SELECT DATEADD(ms,-3,DATEADD(mm, DATEDIFF(m,0,GetDate() )+1, 0)) /*last day of current month*/
-- Last day of prior year
SELECT DATEADD(ms,-3,DATEADD(yy, DATEDIFF(yy,0,GetDate() ), 0)) /*last day of prior year*/
-- Last day of current year
SELECT DATEADD(ms,-3,DATEADD(yy, DATEDIFF(yy,0,GetDate() )+1, 0)) /*last day of current year*/
-- First day of prior month
SELECT DATEADD(mm, DATEDIFF(mm,0,DATEADD(mm,-1-DATEPART(day,GetDate()),GetDate())),0) /*first day of prior month*/
@mikesigs
Copy link
Author

Thank you to Haitham Abu-Rub for these useful SQL queries.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment