How can I reliably convert YYYYMMDDhhmmss<offset> to a date/time?

巧了我就是萌 提交于 2019-12-24 13:15:16

问题


I have a data source where the dates come back like this: 20150614140520-0500

How can I display this better? It doesn't actually have to be converted technically, this is just for reporting. Ideally it would output 2015-06-14 2:05 PM (EST) but I also want the statement to be as simple as possible so the timezone offset and 12hr time are optional.

I tried CAST ('20150614140520-0500' As Date) but it returns null

I also tried CAST (LEFT('20150614140520-0500',14) As Date) as well as some other variants without luck.


回答1:


You have to take the first 14 characters, from the example above:

print convert(datetime,stuff(stuff(stuff(LEFT('20150614140520-0500',14) , 9, 0, ' '), 12, 0, ':'), 15, 0, ':')) 



回答2:


Please try this:

convert(datetime,stuff(stuff(stuff(datevalue, 9, 0, ' '), 12, 0, ':'), 15, 0, ':')) ConvertedDate

As suggested by Dinesh Kumar Rajendran in his blog: https://rdineshkumar.wordpress.com/tag/how-to-convert-yyyymmddhhmmss-to-datetimedatetime-in-sql-server/



来源:https://stackoverflow.com/questions/30877285/how-can-i-reliably-convert-yyyymmddhhmmssoffset-to-a-date-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!