Skip to content
Advertisement

SQL Server: Convert YYYYMMDD-HHMM and YYYYMMDD to mm/dd/yyyy hh:mm

I am trying to convert the time format from YYYYMMDD-HHMM and YYYYMMDD to mm/dd/yyyy hh:mm. My issue is that the data is not consistent. Below is some exemple:

20200814-1230
20200814-1230
20200814     
20200814

I tried to use:

    CONVERT(datetime,LEFT(id,8),120) + ' ' +  
    LEFT(RIGHT(ID , 6) ,2) + ':' + 
    SUBSTRING(RIGHT(ID , 6) , 3,2), 

but the issue is that some data does not have time.

Advertisement

Answer

You can do it like this:

declare @dt varchar(100) = '20200814-1230'

select 
  substring(@dt, 5,2) + '/' +
  substring(@dt, 7,2) + '/' +
  substring(@dt, 1,4) +
  case
    when len(@dt) > 8 then
      ' ' +
      substring(@dt, 10,2) + ':' +
      substring(@dt, 12,2)
    else ''
  end
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement