Print Dates without Day or Time in SQL Server

While designing one of the queries in SQL Server 2005, I came across a requirement to print dates without the day (i.e. only the month and year had to be printed) or print only the time and so on. I had seen a couple of questions on the forums about the same in the past, so thought of sharing these queries in case you needed them.

The original format in which the data was stored was 2010-06-30 14:15:15.390. Just declare it in your sql statement as follows:

DECLARE @CurrentDate DateTime
SET @CurrentDate = '2010-06-30 14:15:15.390'

Here’s how we can achieve the desired output with the @CurrentDate:

Print Date in MM/YYYY format

SELECT DATENAME(m, @CurrentDate) 
+ ' ' + CONVERT(varchar(4), DATEPART(year, @CurrentDate))
as 'MM/YYYY'

OUTPUT
image


Print Date in MM-DD-YY format

SELECT CONVERT(varchar(10), @CurrentDate, 110)
as 'MM-DD-YY'

OUTPUT
image

Print only the Time without the Date

SELECT CONVERT(varchar(8), CURRENT_TIMESTAMP, 112)

OUTPUT
image


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

No comments: