I have a varchar
column which has values like " Aug 07 2017, 04:14 AM,EDT
".
I need to convert this to a date column so that its possible to take the maximum value of the date
.
I tried this:
select CONVERT(datetime, @dateField, 108)
from table
But I am getting the following error:
Conversion failed when converting date and/or time from character string.
You can just use left()
and convert()
:
select convert(date, left('Aug 07 2017, 04:14 AM,EDT', 11))
If you want a datetime then convert the date and time separately, then:
select ( convert(datetime,
left('Aug 07 2017, 04:14 AM,EDT', 11)
) +
convert(datetime,
convert(time,
substring('Aug 07 2017, 04:14 AM,EDT', 14, 8)
)
)
)
Note: This is not taking the time zone into account.
这是一个解决方案:
select CONVERT(datetime, REPLACE(LEFT(@dateField, LEN(@dateField) - 3),',','') ,108 )
Better Datetime solution
DECLARE @dateField AS NVARCHAR(50) = 'Aug 07 2017, 04:14,EDT'
-- Get index of last comma
DECLARE @validDateField AS NVARCHAR(20) = REPLACE(LEFT(@dateField, LEN(@dateField)- CHARINDEX(',', reverse(@dateField))), ',','')
SELECT CONVERT(DATETIME, @validDateField, 108)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.