Introduction: In this article I am going to share the sql query to find
day, month and year from the current or any date using inbuilt DATEPART() or
DAY(), MONTH() and YEAR() functions.
In previous articles i explained How to split string from comma and get left and right part and Concatenate rows values as a comma separated string using for xml path and stuff in sql server and Count number of occurrences of character or word in a string in sql and Remove first or last character from string or column in sql server and Try catch to handle exception and commit/rollback transaction
Description: Many times we need to get the day, month or year part from the date. Sql server provides functions to get any part from the date/time. Here i have used DATEPART() and DAY(), MONTH() and YEAR() functions to get any part as per requirement. Here I am using current date from demonstration purpose. just replace the GETDATE() with the actual date if you want to get day, month and year from any other date.
Implementation: Let’s write a sample query to get the desired result
Using DATEPART() to get Day,
Month and Year from current date
SELECT DATEPART(D,GETDATE()) AS Day, DATEPART(M,GETDATE()) AS Month, DATENAME(YY,GETDATE()) AS Year
OR
SELECT DATEPART(DD,GETDATE()) AS Day, DATEPART(MM,GETDATE()) AS Month, DATENAME(YYYY,GETDATE()) AS Year
OR
SELECT DATEPART(DAY,GETDATE()) AS Day, DATEPART(MONTH,GETDATE()) AS Month, DATENAME(YEAR,GETDATE()) AS Year
Using DAY(), MONTH() and YEAR()
functions to get Day, Month and Year from current date
SELECT DAY(GETDATE()) AS Day, MONTH(GETDATE()) AS Month, YEAR(GETDATE()) AS Year
Result:
Result:
Day
|
Month
|
Year
|
12
|
3
|
2016
|
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..