Reputation: 594
I have a Calendar table with the following structure:
CalendarID nvarchar(13)
Date date
Time time(7)
with data such as:
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]
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]
How can I format it as hh:mm
?
Upvotes: 2
Views: 1987
Reputation: 3814
The FORMAT() function doesn't work well with the TIME datatype. The solution is to first convert the TIME to a DATETIME before formatting...
DECLARE @CurrentTime AS TIME = GETDATE();
The Problem: Format returns NULL for the current time when you pass it a TIME.
SELECT @CurrentTime AS TimeUnformatted, FORMAT(@CurrentTime, 'hh:mm tt') AS CurrentTime;
The Solution: Cast the time as a DATETIME before formatting.
SELECT FORMAT(CAST(@CurrentTime AS DATETIME), 'hh:mm tt') AS CurrentTime;
Upvotes: -1
Reputation: 29
It appears to be very picky about input types. This will return NULL:
declare @theNow as time
set @theNow = cast(getdate() as time)
print format(@theNow, N'hh\:mm tt')
whereas this will print your expected result string:
declare @theNow as datetime
set @theNow = cast(getdate() as datetime)
print format(@theNow, N'hh\:mm tt')
I'm still trying to work out the details myself.
Upvotes: 2
Reputation: 30625
Try it in this way:
FORMAT([Time], N'hhmm') AS [Time]
or
FORMAT([Time], N'hh\:mm') AS [Time]
Upvotes: 3
Reputation: 248
You may want to check the docs about date and datetime
After Larnu's warning
Update:
From the above link you can format the time like that;
SELECT FORMAT(cast(GETDATE() as time), N'hh\:mm\:ss');
Upvotes: 1
Reputation: 272236
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
Upvotes: 3