简体   繁体   English

从字符串转换为dd / MM / yyyy

[英]Convert to dd/MM/yyyy from character string

I have the following output that is stored in a string field: 我将以下输出存储在字符串字段中:

Query 询问

SELECT StringField5 FROM MyTable WHERE OrderID=1

Output 产量

02/13/2018 2018年2月13日

I would like to use one of the ways SQL allow to convert/cast to get the following output: 我想使用SQL允许转换/广播的一种方法来获取以下输出:

13/02/2018. 13/02/2018。

I have tried the following code and a lot of them found on this website but none helped and always returned the first output described (02/13/2008): 我尝试了以下代码,但在此网站上找到了很多代码,但没有帮助,总是返回描述的第一个输出(02/13/2008):

SELECT CONVERT(varchar(25), StringField5, 103) FROM MyTable WHERE OrderID=1

I'm using SQL Server 2016. 我正在使用SQL Server 2016。
What am I missing? 我想念什么?

First convert your string date to a datetime, then convert that datetime back to the string output you expect: 首先将您的字符串日期转换为日期时间,然后将该日期时间转换回您期望的字符串输出:

SELECT CONVERT(varchar(25), CONVERT(datetime, '02/13/2018', 101), 103)
FROM MyTable
WHERE OrderID = 1;

Demo 演示

By the way, it is generally a bad idea to store your dates in the database as strings. 顺便说一句,将日期作为字符串存储在数据库中通常是个坏主意。 Always store your information as formal dates. 始终将您的信息存储为正式日期。

You should use 你应该用

SELECT FORMAT(StringField5, 'dd/MM/yyyy', 'en-US' ) FROM MyTable WHERE OrderID=1

See the FORMAT 格式

您可以使用此方法将'02 / 13/2018'转换为'13 / 02/2018'

Select substring(StringField5,4,2)+'/'+ substring(StringField5,0,3)+'/'+ substring(StringField5,7,4) FROM MyTable WHERE OrderID=1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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