DATEPART() Function in SQL Server
Last Updated :
18 Jan, 2021
DATEPART() function :
This function in SQL Server is used to find a given part of the specified date. Moreover, it returns the output value as an integer.
Features :
- This function is used to find a given part of the specified date.
- This function comes under Date Functions.
- This function accepts two parameters namely interval and date.
- This function can also include time in the date section.
- This function returns the output in integer form.
Syntax :
DATEPART(interval, date)
Parameter :
This method accepts two parameters as given below as follows.
- interval –
It is the specified part which is to be returned. Moreover, the values of the interval can be as given below.
year, yyyy, yy = Year, which is the specified year.
quarter, qq, q = Quarter, which is the specified quarter.
month, mm, m = month, which is the specified month.
dayofyear, dy, y = Day of the year, which is the specified day of the year.
day, dd, d = Day, which is the specified day.
week, ww, wk = Week, which is the specified week.
weekday, dw, w = Weekday, which is the specified week day.
hour, hh = hour, which is the specified hour.
minute, mi, n = Minute, which is the specified minute.
second, ss, s = Second, which is the specified second.
millisecond, ms = Millisecond, which is the specified millisecond.
- date –
It is the specified date which is to be used.
Returns :
It returns a given part of the specified date.
Example-1 :
Using DATEPART() function and getting the year part of the specified date.
SELECT DATEPART(year, '2017/08/25');
Output :
2017
Example-2 :
Using DATEPART() function and getting the month part of the specified date.
SELECT DATEPART(month, '2017/08/25');
Output :
8
Example-3 :
Using DATEPART() function and getting the day part of the specified date.
SELECT DATEPART(day, '2017/08/25');
Output :
25
Example-4 :
Using DATEPART() function and getting the hour part of the specified date which includes time as well.
SELECT DATEPART(hour, '2021/01/06 05:30');
Output :
5
Example-5 :
Using DATEPART() function and getting the second part of the specified date which includes time as well using a variable.
DECLARE @date VARCHAR(50);
SET @date = '2019/06/05 07:37:54';
SELECT DATEPART(second, @date);
Output :
54
Application :
This function is used to find the given part of the specified date.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...