SQL - Converting 24-hour (“military”) time (2145) to “AM/PM time” (9:45 pm)

前端 未结 7 1176
一向
一向 2020-12-21 00:09

I have 2 fields I\'m working with that are stored as smallint military structured times.
Edit I\'m running on IBM Informix Dynamic Server Version 10.00.FC9

7条回答
  •  长情又很酷
    2020-12-21 00:56

    Here's a non-tested port of Steve Kass's solution to Informix.

    Steve's solution itself is well tested under MS SQL Server. I like it better than my previous solutions because the conversion to am/pm time is exclusively done algebraically not requiring the help of any branching (with CASE statements and such).

    Substitute the @milTime with column name if the numeric "military time" comes from the database. The @ variable is only there for test.

    --declare @milTime int
    --set @milTime = 1359
    SELECT
      CAST(MOD((@milTime /100 + 11), 12) + 1 AS VARCHAR(2))
      ||':'
      ||SUBSTRING(CAST((@milTime%100 + 100) AS CHAR(3)) FROM 2 FOR 2)
      ||' '
      || SUBSTRING('ap' FROM (MOD(@milTime / 1200, 2) + 1) FOR 1)
      || 'm';
    

    For reference here's my [fixed], CASE-based, solution for SQL Server

    SELECT 
      CASE ((@milTime / 100) % 12)
          WHEN 0 THEN '12'
          ELSE CAST((@milTime % 1200) / 100 AS varchar(2))
      END 
      + ':' + RIGHT('0' + CAST((@milTime % 100) AS varchar(2)), 2)
      + CASE (@milTime / 1200) WHEN 0 THEN ' am' ELSE ' pm' END
    

提交回复
热议问题