简体   繁体   English

将字符串转换为日期时间 - SQL

[英]Convert string to datetime - SQL

I have a string parsed from XML which represents datetime.我有一个从 XML 解析的字符串,它表示日期时间。 String format is: '20200915114000' - (YYYYMMDDhhmmss)字符串格式为:'20200915114000' - (YYYYMMDDhhmmss)

Is there a function in SQL Server to convert or parse this string to datetime or should I split string manually and concatenate it into datetime? SQL Server 中是否有函数可以将此字符串转换或解析为日期时间,还是应该手动拆分字符串并将其连接为日期时间?

How to do this, in 3 steps:如何做到这一点,分 3 个步骤:

C:\> SQLCMD
1> select convert(datetime,'20200915114000' )
2> go
Msg 241, Level 16, State 1, Server ZES, Line 1
Conversion failed when converting date and/or time from character string.
1> select convert(datetime,'20200915 114000' )
2> go
Msg 242, Level 16, State 3, Server ZES, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
1> select convert(datetime,'20200915 11:40:00' )
2> go

-----------------------
2020-09-15 11:40:00.000

(1 rows affected)
1>

Conclusion you need to add a space and 3 ':' in the string to convert '20200915114000' to '20200915 11:40:00' .结论您需要在字符串中添加一个空格和 3 个 ':' 以将'20200915114000'转换为'20200915 11:40:00' After this a simple CONVERT will do the trick.在此之后,一个简单的 CONVERT 就可以解决问题。

Solution to my problem:我的问题的解决方案:

declare @sDate char(14), @sDateOK char(20)

set @sDate = '20200915114000'    
set @sDateOK = substring(@sDate,1,8) + ' ' + substring(@sDate,9,2) + ':' +  substring(@sDate,11,2) + ':' +  substring(@sDate,13,2)

select convert(datetime,@sDateOK ) as Date

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

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