Cast or convert DD-MON-YYYY AM/PM to YYYY-MM-DD

六眼飞鱼酱① 提交于 2019-12-11 07:52:29

问题


I'm stuck in finding an answer on how to convert: 07-DEC-18 01.00.54.984000 PM to 2018-12-07 13.00.54.984000

I think the time of 01.00.54 PM is 13hours , 0 minutes and 54 seconds

I have try to convert with 112 but still i can't find out how to cast or convert this.


回答1:


Below is one method that converts the date and time portions separately, and then uses DATEADD to combine the results. This assumes the actual time precision is not greater than milliseconds. Note that you need to use datetime2 instead of datetime to avoid rounding to 1/300 milliseconds.

DECLARE @DateTimeString varchar(30) = '07-DEC-18 01.00.54.984000 PM';
SELECT DATEADD(
      millisecond
    , DATEDIFF(millisecond, '', CAST(REPLACE(SUBSTRING(@DateTimeString, 11, 8), '.', ':') + RIGHT(@DateTimeString, 10) AS time))
    , CAST(LEFT(@DateTimeString, 9) AS datetime2)
    );



回答2:


This converts your value to the datatype it should be, a datetime2(6). Date and time datatypes don't have formats, if you're storing them in a particular format you're doing it wrong (as it means you're storing the value as a varchar).

DECLARE @YourDate varchar(30) = '07-DEC-18 01.00.54.984000 PM';

SELECT V.YD,
       TRY_CONVERT(datetime2(6),F.FormatedYD,106)
FROM (VALUES(@YourDate)) V(YD)
     CROSS APPLY (VALUES(STUFF(STUFF(V.YD,13,1,':'),16,1,':'))) F(FormatedYD);

If this was a table, then I would fix your actual column datatype by doing the following:

UPDATE YT
SET YourDateColumn = CONVERT(varchar(30),TRY_CONVERT(datetime2(6),F.FormatedYD,106),126)
FROM YourTable YT
     CROSS APPLY (VALUES(STUFF(STUFF(YT.YourDateColumn,13,1,':'),16,1,':'))) F(FormatedYD);

ALTER TABLE YourTable ALTER COLUMN YourDateColumn datetime2(6);


来源:https://stackoverflow.com/questions/53682302/cast-or-convert-dd-mon-yyyy-am-pm-to-yyyy-mm-dd

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