如何在 SQL Server 中将日期时间格式化为 M/D/YYYY?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26662725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to format datetime as M/D/YYYY in SQL Server?
提问by pkr298
To convert a datetime
to MM/DD/YYYY
, this works:
要将 a 转换datetime
为MM/DD/YYYY
,这有效:
declare @datetime datetime = '2015-01-01'
select convert(varchar(10),convert(date,@datetime),101)
This evaluates to 01/01/2015
. How can I have the date convert to 1/1/2015
instead?
这评估为01/01/2015
. 我怎样才能将日期转换为1/1/2015
?
Nothing on http://www.sql-server-helper.com/tips/date-formats.aspxmatches the M/D/YYYY
format.
http://www.sql-server-helper.com/tips/date-formats.aspx 上没有任何内容与M/D/YYYY
格式匹配。
回答by Donal
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:
使用 SQL Server 2012 及更高版本,您可以执行以下操作:
SELECT FORMAT(@datetime, 'M/d/yyyy')
回答by sqluser
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 '/'
- 首先将日期时间转换为字符
- 然后在开头添加一个“/”字符
- 用“/”替换所有“/0”
- 使用 STUFF,去掉第一个 '/'
回答by Jaaz Cole
There's no convert style that uses single digit day or month. This could work, though.
没有使用单位数日或月的转换样式。不过,这可以奏效。
declare @datetime datetime = '2015-01-01'
select
cast(month(@datetime) as varchar(2)) + '/' +
cast(day(@datetime) as varchar(2)) + '/' +
cast(year(@datetime) as varchar(4))