-1

How to convert “Thu Jun 11 00:49:35 IST 2015” to “YYYY-MM-DD hh:mm:ss” in SQL Server?

I tried to convert and casting but it's throwing an error

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

1 Answers1

0

A few things to note about this before I posit a solution:

  • The source of this information should be modified, if at all possible, to conform to some ISO-standard date.
  • SQL Server pre-2016 doesn't handle time zone names well, so I'm going to presume that all of your strings contain "IST". If they don't, you'll have to adjust accordingly by searching for them and creating some kind of switch case to modify the resulting datetimeoffset.
  • I have no idea whether your day representation is two-digit or variable-digit. I've assumed that it's variable, but you can probably simplify this answer with fixed-string parsing if it's two-digit.
  • Since you have a timezone, the target representation of YYYY-MM-DD hh:mm:ss is ambiguous. I've converted it here to UTC.

If your string is in a table called Dates with column HorribleString, then:

select
  convert(varchar(100), convert(datetime2, convert(datetimeoffset, 
    substring(HorribleString, len(HorribleString) - 3, 4) -- Year
    + substring(HorribleString, 4, len(HorribleString) - 12) -- len(Thu ) + len( IST 2015) = 12
    + case substring(HorribleString, len(HorribleString) - 7, 3) -- Timezone
        when 'IST' then ' +05:30'
        else ''
      end
  , 109), 1), 20)
from
  Dates
Jeremy Fortune
  • 2,459
  • 1
  • 18
  • 21