SQL Server DATEPART() Function
Definition and Usage
The DATEPART() function is used to return individual parts of a date/time, such as year, month, day, hour, minute, etc.
Syntax
DATEPART(datepart,date)
date The parameter is a valid date expression.datepart The parameter can be one of the following values:
datepart | Abbreviations |
---|---|
Years | yy, yyyy |
Quarters | qq, q |
Months | mm, m |
Day of the Year | dy, y |
Days | dd, d |
Weeks | wk, ww |
Weeks | dw, w |
Hours | hh |
Minutes | mi, n |
Seconds | ss, s |
Milliseconds | ms |
Microseconds | mcs |
Nanoseconds | ns |
Example
Assuming we have the following 'Orders' table:
OrderId | ProductName | OrderDate |
---|---|---|
1 | 'Computer' | 2008-12-29 16:25:46.635 |
We use the following SELECT statement:
SELECT DATEPART(yyyy,OrderDate) AS OrderYear, DATEPART(mm,OrderDate) AS OrderMonth, DATEPART(dd,OrderDate) AS OrderDay FROM Orders WHERE OrderId=1
Result:
OrderYear | OrderMonth | OrderDay |
---|---|---|
2008 | 12 | 29 |