Search code examples
sqlsql-serverdatetimeformat

FORMAT([Time], 'hh:mm') returns NULL


I have a Calendar table with the following structure:

CalendarID    nvarchar(13)
Date          date
Time          time(7)

with data such as:

Calendar table data

Formatting the time column as hhmm works:

SELECT [CalendarID]
     , FORMAT([Date], 'ddd, MMM dd, yyyy') AS [DATE]
     , FORMAT([Time], 'hhmm') AS [Time]
FROM [dbo].[Calendar]

select time format (hhmm)

But formatting as hh:mm does not work and displays NULL:

SELECT [CalendarID]
     , FORMAT([Date], 'ddd, MMM dd, yyyy') AS [DATE]
     , FORMAT([Time], 'hh:mm') AS [Time]
FROM [dbo].[Calendar]

select time format (hh:mm)

How can I format it as hh:mm?


Solution

  • From the docs:

    FORMAT relies upon CLR formatting rules, which dictate that colons and periods must be escaped. Therefore, when the format string (second parameter) contains a colon or period, the colon or period must be escaped with backslash when an input value (first parameter) is of the time data type.

    This should work:

    SELECT FORMAT(CAST('09:00:00.1234567' AS TIME(7)), 'hh\:mm')              -- 09:00
    SELECT FORMAT(CAST('09:00:00.1234567' AS TIME(7)), 'hh\:mm\:ss\.fffffff') -- 09:00:00.1234567