将 SQL Server 日期转换为 mm-yyyy
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28842873/
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
Convert SQL Server Date to mm-yyyy
提问by Prateek Daniels
I'm trying to convert my Date which is (eg. 2012-04-20 05:54:59) format in into mm-yyyy. I came across some solutions that says you would need to convert into varchar . Is there any way using the Convert function ?
我正在尝试将我的日期(例如 2012-04-20 05:54:59)格式转换为 mm-yyyy。我遇到了一些解决方案,说您需要转换为 varchar 。有什么办法可以使用 Convert 函数吗?
Thanks :)
谢谢 :)
回答by Giorgos Betsos
You can use FORMAT
function, available from SQL Server 2012 onwards:
您可以使用FORMAT
从 SQL Server 2012 开始可用的函数:
DECLARE @myDate DATETIME = '2012-04-20 05:54:59'
SELECT FORMAT(@myDate, 'MM-yyyy')
Output:
输出:
04-2012
回答by Jim Horn
There might be a more graceful way to pull this off, but the below works.
可能有一种更优雅的方式来解决这个问题,但下面的方法有效。
Declare @dt datetime = GETDATE()
SELECT LEFT('0' + CAST(MONTH(@dt) as varchar(2)),2) + '-' + CAST(YEAR(@dt) as char(4))
btw my normal Date Conversion cheat sheet is here, but I'm not seeing MM-YYYY as one of the formats.
顺便说一句,我的普通日期转换备忘单在这里,但我没有将 MM-YYYY 视为其中一种格式。
回答by Dudi Konfino
select [MM-YYYY] = right(convert(varchar(10),getdate(),105),7)
回答by sqluser
As you are using SQL Server 2014, You can use FORMAT
which is the best also you can apply this:
当您使用 SQL Server 2014 时,您可以使用FORMAT
哪个是最好的,您也可以应用它:
SELECT CONVERT(VARCHAR(2),MONTH(yourDateTimeField)) + '-' +
CONVERT(VARCHAR(4),YEAR(yourDateTimeField)) AS [MM-YYYY]
FROM yourTable
ORDER BY yourDateTimeField