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

白昼怎懂夜的黑 提交于 2019-12-21 07:55:42

问题


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?


回答1:


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.




回答2:


You can use the FORMAT function, which is built for just this sort of thing, although I agree that if you can wait to format it on the client side you may be better off as you give yourself the flexibility to use that data as a date at any point along the line (ymmv - just more of a best practice).

Example:

FORMAT ( table.myDateColumn, 'd', 'en-US' )

See http://msdn.microsoft.com/en-us/library/hh213505.aspx

May not be available in older versions of SQL Server




回答3:


You could do:

STUFF(REPLACE('/'+CONVERT(CHAR(10), Citation.PublishedOn ,101),'/0','/'),1,1,'')

(Based on http://www.sqlservercentral.com/Forums/Topic1241877-1292-1.aspx.)




回答4:


I took a different approach, which is more of a trick:

REPLACE(REPLACE('a'+ @table.date ),'a0',''),'a','')

I thought it was spiffy, but I got the idea after interpreting the STUFF trick above incorrectly. :)



来源:https://stackoverflow.com/questions/6128558/in-sql-server-how-to-convert-a-date-to-a-string-in-format-m-d-yyyy-no-leading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!