Introduction:
In this article I am going to share how to extract date, time, year, month,
day, hour, minute, second, millisecond portion from any specified date in Sql
server using DATEPART() function.
In previous articles i explained the Query to get age in years, months and days from date of birth and Query to get upcoming birthdays within week and Copy all data from one table to another in the same database in sql server and Get difference in days, hours, minutes and seconds between two dates in sql server and Pass month and year value and get first, last and total days in that month
DECLARE @CurrentDate DATETIME=GETDATE();
SELECT @CurrentDate AS CurrentDate
SELECT CONVERT(VARCHAR(10), GETDATE(), 111) 'Date Part'
SELECT CONVERT(VARCHAR(8), GETDATE(), 108) As 'Time Part(hh:mm:ss)'
SELECT DATEPART(YEAR,@CurrentDate) AS 'Year Part'
SELECT DATEPART(MONTH,@CurrentDate) AS 'Month Part'
SELECT DATEPART(DAY,@CurrentDate) AS 'Day Part'
SELECT DATEPART(HOUR,@CurrentDate) AS 'Hour Part'
SELECT DATEPART(MINUTE,@CurrentDate) AS 'Minute Part'
SELECT DATEPART(SECOND,@CurrentDate) AS 'Second Part'
SELECT DATEPART(MILLISECOND,@CurrentDate) AS 'MilliSecond Part'
Output will be as:
CurrentDate
|
2016-10-10
22:34:48.370
|
Date Part
|
2016/10/10
|
Time Part(hh:mm:ss)
|
22:34:48
|
Year Part
|
2016
|
Month Part
|
10
|
Day Part
|
10
|
Hour Part
|
22
|
Minute Part
|
34
|
Second Part
|
48
|
MilliSecond Part
|
370
|
Year, Month and Day part can also be extracted using the sql inbuilt functions Year, Month and Day as:
SELECT YEAR(@CurrentDate) AS 'Year Part'
SELECT MONTH(@CurrentDate) AS 'Month Part'
SELECT DAY(@CurrentDate) AS 'Day Part'
Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates.
If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..