In SQL Server, how to convert a date to a string in format M/D/YYYY? (no leading zeros, not MM/DD/YYYY)

thursdaysgeek picture thursdaysgeek · May 25, 2011 · Viewed 26k times · Source

Right now, my code has the following conversion for a date field:

convert(varchar, Citation.PublishedOn, 101)

However, that returns dates like 03/01/2010. The request was to have the dates display as 3/1/2010 (without the leading zeros, but with a 4 digit year). I've looked at http://msdn.microsoft.com/en-us/library/ms187928.aspx and I'm not seeing anything that explicitly excludes leading zeros.

How do I format the date to exclude leading zeros?

Answer

Mark Costello picture Mark Costello · May 25, 2011

This is how I would do it:

DECLARE @dt datetime
SET @dt= Citation.PublishedOn
SELECT LTRIM(STR(MONTH(@dt)))+'/'+LTRIM(STR(DAY(@dt)))+'/'+STR(YEAR(@dt),4)

You select your date, then extract the day, month and year from it and chop the leading zeroes off the month and day using ltrim().

If you don't want to declare a variable, you can do this

SELECT LTRIM(STR(MONTH(Citation.PublishedOn)))+'/'+LTRIM(STR(DAY(Citation.PublishedOn)))+'/'+STR(YEAR(Citation.PublishedOn),4)

However, that would mean pulling out the same value multiple times.