Michael Murphy Michael Murphy - 1 month ago 14
SQL Question

DateTime convert from varchar

I'm looking for some help. I have a date field as 2015/08/08T12:00GMT for a school project. I have only had one class on sql, so Im really new to this. My situation is this:

I need the

varchar(50)
2015/08/08T12:00GMT converted to a date type. I dont know how to do this in sql. I have tired cast, and convert, and I keep getting errors, and failures on conversion.

I have been searching, and trying different methods, just not getting results. Any help would be so appreicated, thank you!

Answer

Here's an idea to get you thinking about possible approaches and solutions:

declare @T varchar(100) = '2015/08/08T12:00GMT';
select
    convert(
        datetime,
        replace(
            case when right(@T, 3) in ('GMT', 'UTC')
                then left(@T, len(@T) - 3) + ':00Z'
                else @T
            end,
            '/', '-'
        ),
        127
    );

The documentation spells out the formats recognized by the function convert().

Comments