问题
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