Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Useful DateTime Functions

4.59/5 (23 votes)
5 Mar 2015CPOL 78K  
Reminder.Sou...

Reminder.

Source

SQL
----Today
SELECT GETDATE() 'Today'
----Yesterday
SELECT DATEADD(d,-1,GETDATE()) 'Yesterday'

--Start of Current Day
SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0) 'Start of Current Day'
--End of Current day
SELECT DATEADD(ms,-3,DATEADD(dd,DATEDIFF(dd,0,GETDATE()),1)) 'End of Current day' 

--Start of Yesterday
SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),-1) 'Start of Yesterday'
--End of Yesterday
SELECT DATEADD(ms,-3,DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0)) 'End of Yesterday' 

--First day of week by ISO
SELECT DATEADD(dd,7*(DATEDIFF(dd,'1973-01-01',GETDATE())/7),'1973-01-01') 'First day of current ISO Week'

----First Day of Current Week
SELECT DATEADD(wk,DATEDIFF(wk,0,GETDATE()),0) 'First Day of Current Week'
----Last Day of Current Week
SELECT DATEADD(wk,DATEDIFF(wk,0,GETDATE()),6) 'Last Day of Current Week'
----First Day of Last Week
SELECT DATEADD(wk,DATEDIFF(wk,7,GETDATE()),0) 'First Day of Last Week'
----Last Day of Last Week
SELECT DATEADD(wk,DATEDIFF(wk,7,GETDATE()),6) 'Last Day of Last Week'
----First Day of Current Month
SELECT DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0) 'First Day of Current Month'
----Last Day of Current Month
SELECT DATEADD(ms,- 3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,GETDATE())+1,0))) 'Last Day of Current Month'
----First Day of Last Month
SELECT DATEADD(mm,-1,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0)) 'First Day of Last Month'
----Last Day of Last Month
SELECT DATEADD(ms,-3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0))) 'Last Day of Last Month'
----First Day of Current Quarter
SELECT DATEADD(qq,DATEDIFF(qq,0,GETDATE()),0) 'First Day of Current Quarter'
----First Day of Current Year
SELECT DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0) 'First Day of Current Year'
----Last Day of Current Year
SELECT DATEADD(ms,-3,DATEADD(yy,0,DATEADD(yy,DATEDIFF(yy,0,GETDATE())+1,0))) 'Last Day of Current Year'
----First Day of Last Year
SELECT DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0)) 'First Day of Last Year'
----Last Day of Last Year
SELECT DATEADD(ms,-3,DATEADD(yy,0,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))) 'Last Day of Last Year' <font color="#111111" face="Segoe UI, Arial, sans-serif"><span style="font-size: 14px"> </span></font>

--Date of Monday of current week
SELECT DATEADD(dd,7*(DATEDIFF(dd,'1973-01-01',GETDATE())/7),'1973-01-01') Date_Week
 <font color="#111111" face="Segoe UI, Arial, sans-serif"><span style="font-size: 14px">
</span></font>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)