SQL Server DATEPART() Function
The DATEPART()
function in SQL Server extracts a specific part (year, month, day, hour, minute, second, etc.) from a date or datetime value. It's a very useful function for working with dates and times.
DATEPART(): Definition and Usage
DATEPART()
allows you to isolate individual components of a date or time. This is extremely helpful for filtering, grouping, or calculating based on specific parts of a date. The returned value is always an integer.
Syntax
Syntax
DATEPART(interval, date)
Parameter Values
Parameter | Description |
---|---|
interval |
The part of the date to extract. Options:
|
date |
The date or datetime value. Can be: date , datetime , datetimeoffset , datetime2 , smalldatetime , or time . This is required. |
Examples
Extracting the Year
Getting the year from the date '2017/08/25'.
Syntax
SELECT DATEPART(year, '2017/08/25') AS DatePartInt;
Output
2017
Extracting the Year (alternative syntax)
Another way to get the year.
Syntax
SELECT DATEPART(yy, '2017/08/25') AS DatePartInt;
Output
2017
Extracting the Month
Getting the month from the date.
Syntax
SELECT DATEPART(month, '2017/08/25') AS DatePartInt;
Output
8
Extracting the Hour
Getting the hour from a datetime value.
Syntax
SELECT DATEPART(hour, '2017/08/25 08:36') AS DatePartInt;
Output
8
Extracting the Minute
Getting the minute from a datetime value.
Syntax
SELECT DATEPART(minute, '2017/08/25 08:36') AS DatePartInt;
Output
36