SQL 将 dd/mm/yy 字符串转换为 yyyy-mm-dd

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14445882/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:14:04  来源:igfitidea点击:

Convert dd/mm/yy string to yyyy-mm-dd

sqlsql-server

提问by Jeremy1026

I am having issues converting a string in dd/mm/yy hh:mi:ssformat to yyyy-mm-dd hh:mi:ssformat.

我在将字符串dd/mm/yy hh:mi:ss格式转换为yyyy-mm-dd hh:mi:ss格式时遇到问题。

I have tried using CONVERT()as follows:

我尝试使用CONVERT()如下:

select CONVERT(VARCHAR, '11/10/11 10:56:58', 120)

But that returns no change:

但这不会带来任何变化:

11/10/11 10:56:58

回答by Aaron Bertrand

You need to convert to datetime first to change a string to reflect a certain regional format. Be sure you are interpreting the datetime value correctly, too; on some systems, that will be October 11th, on others it will be November 10th.

您需要先转换为日期时间以更改字符串以反映某种区域格式。确保您也正确解释了日期时间值;在某些系统上,这将是 10 月 11 日,而在其他系统上,它将是 11 月 10 日。

SELECT CONVERT(CHAR(19), CONVERT(DATETIME, '11/10/11 10:56:58', 3), 120);

Finally, use the correct number of characters in your charor varchardeclarations. Not specifying a length is lazy and can lead to problems. See:

最后,在您的charorvarchar声明中使用正确数量的字符。不指定长度是懒惰的,可能会导致问题。看:

回答by Lamak

This will work:

这将起作用:

SELECT CONVERT(VARCHAR(19),CONVERT(DATETIME,'11/10/11 10:56:58',3),120)

回答by Francis P

The issue: you are converting a VARCHAR to a VARCHAR.

问题:您正在将 VARCHAR 转换为 VARCHAR。

Your query is fine if you use a DATETIME.

如果您使用 DATETIME,您的查询就可以了。

SELECT CONVERT(VARCHAR(19), CAST('11/10/11 10:56:58' AS DATETIME), 120);

See fiddle.

小提琴