SQL Server DATENAME() Function
The DATENAME()
function in SQL Server extracts a specific part (year, month, day, hour, minute, etc.) from a date or datetime value and returns it as a string. This is very useful for formatting dates and times or for creating more human-readable outputs.
DATENAME(): Definition and Usage
Unlike DATEPART()
, which returns the date part as an integer, DATENAME()
returns it as a string. This makes it especially convenient for generating reports or displaying dates in a user-friendly format. For example, you might use it to display the month name instead of the month number.
Syntax
Syntax
DATENAME(interval, date)
Parameter Values
Parameter | Description |
---|---|
interval |
The part of the date to extract. Options:
|
date |
The date or datetime value. This is required. |
Examples
Extracting the Year
This extracts the year as a string from the date '2017/08/25'.
Syntax
SELECT DATENAME(year, '2017/08/25') AS DatePartString;
Output
2017
Extracting the Year (alternative syntax)
Another way to get the year as a string.
Syntax
SELECT DATENAME(yy, '2017/08/25') AS DatePartString;
Output
17
Extracting the Month
Getting the month name as a string.
Syntax
SELECT DATENAME(month, '2017/08/25') AS DatePartString;
Output
August
Extracting the Hour
Getting the hour from a datetime value.
Syntax
SELECT DATENAME(hour, '2017/08/25 08:36') AS DatePartString;
Output
08
Extracting the Minute
Getting the minute from a datetime value.
Syntax
SELECT DATENAME(minute, '2017/08/25 08:36') AS DatePartString;
Output
36