Convert Date to String in SQL Server

Whenever I see a question on converting a Date to String in SQL Server, I see developers nesting various REPLACE functions to get the desired output. However with some knowledge of formatting date and time, this requirement can be achieved in a simple manner as shown below.

Here’s a query that converts a Date to a String in SQL Server:

DECLARE @Dt as DateTime
SET
@Dt = '2010-04-27 11:30:17'

SELECT CONVERT(CHAR(8), @Dt, 112)
+
REPLACE(CONVERT(CHAR(8), @Dt, 114), ':', '')

In the query shown above, the style value 112 gives an output of yymmdd and a style value 114, gives an output of hh:mi:ss:mmm(24h). To display the milliseconds too, change Char(8) to Char(12).

OUTPUT

Date to String

Further Reading: Cast and Convert


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: