简体   繁体   中英

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

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

I have tried using CONVERT() as follows:

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

But that returns no change:

11/10/11 10:56:58

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.

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

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

这将起作用:

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

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

Your query is fine if you use a DATETIME.

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

See fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM