Convert SQL Date MMDDYY varchar to Date?
-
23-01-2021 - |
Question
In reading this,
http://www.sqlusa.com/bestpractices/datetimeconversion/
I cannot locate the answer.
How do I convert varchar '060118' (MMDDYY) to date?
Solution
There is no method to directly convert this value because SQL implicitly assumes the first two characters are the year when directly converting to DATE and there is no option for providing a custom format mask.
You need to manipulate the string value first to produce a string that you can then convert to a datetime value.
DECLARE @Val VARCHAR(25) = '060118'
SELECT CONVERT(DATETIME, SUBSTRING(@Val, 5, 2) + SUBSTRING(@Val, 1, 2) + SUBSTRING(@Val, 3, 2) , 101)
Result:
06/01/2018
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange