Search code examples
sqlsql-serversql-server-2005

Convert Military time to string representation


I have an column declared as int (called HourMil) which stores the time in military format. I need to convert this values to an formatted string (HH:MM)

example

HourMil  = 710 -> must be 07:10
HourMil  = 1305 -> must be 13:05

Actually I am using this code (and works ok) for convert the column HourMil to the string representation.

SELECT SUBSTRING(LEFT('0',4-LEN(CAST(HourMil AS VARCHAR)))+CAST(HourMil AS VARCHAR),1,2)+':'+SUBSTRING(LEFT('0',4-LEN(CAST(HourMil AS VARCHAR)))+CAST(HourMil AS VARCHAR),3,2) FROM MYTABLE

but I think this code can be improved.


Solution

  • By creating a date, then formatting it:

    SELECT SUBSTRING(CONVERT(nvarchar, DATEADD
       (hh, HourMil / 100, DATEADD(mi, HourMil % 100, '1900-01-01')), 8), 0, 6)