Categories
Date Linux Query SQL Time Windows

SQL: How to extract Year, Month, Day, Hour, Minute and Seconds from a DateTime

The DATEPART function accepts two parameters :

DATEPART ( datepart , date ) where
datepart – specifies the part of the date to return. For eg: year, month and so on
date – is the datetime or smalldatetime value

QUERY

SELECT
DATEPART(year, GETDATE()) as ‘Year’,
DATEPART(month,GETDATE()) as ‘Month’,
DATEPART(day,GETDATE()) as ‘Day’,
DATEPART(week,GETDATE()) as ‘Week’,
DATEPART(hour,GETDATE()) as ‘Hour’,
DATEPART(minute,GETDATE()) as ‘Minute’,
DATEPART(second,GETDATE()) as ‘Seconds’,
DATEPART(millisecond,GETDATE()) as ‘MilliSeconds’

Note: When using a smalldatetime, only information up to the ‘minute’ gets displayed. Seconds and milliseconds are always 0.