How to format datetime as M/D/YYYY in SQL Server?
I think the only possibility you have is to do something like this:
DECLARE @datetime DATETIME = '2015-01-01'
SELECT LTRIM(STR(MONTH(@datetime))) + '/' +
LTRIM(STR(DAY(@datetime))) + '/' +
STR(YEAR(@datetime), 4)
With SQL Server 2012 and above, you can do this:
SELECT FORMAT(@datetime, 'M/d/yyyy')
DECLARE @datetime DATETIME = '2015-01-01';
SELECT STUFF(REPLACE('/' + CONVERT(CHAR(10), @datetime, 101),'/0','/'),1,1,'')
This is how it works:
- First CONVERT the DATETIME to CHAR
- Then Add a '/' character at the begining
- REPLACE all '/0' with '/'
- With STUFF, get rid of the first '/'