How do you use the FORMAT function with the 'D' and 'T' format strings to format dates and times in SQL Server?
Posted by SamPetr
Last Updated: July 13, 2024
In SQL Server, the FORMAT function is used to format dates and times based on specific format strings. The 'D' and 'T' format strings are used to represent long date and long time formats, respectively. Here’s how you can use them:
FORMAT with 'D' - Long Date Format
The 'D' format string returns the date in a long date format, which includes the full name of the day, month, and the year. The exact output of the 'D' format can vary based on the server's locale settings. Example:
DECLARE @date DATE = '2023-10-05';
SELECT FORMAT(@date, 'D') AS LongDate;
This will return the date formatted in a long date style, such as "Thursday, October 5, 2023", depending on your locale settings.
FORMAT with 'T' - Long Time Format
The 'T' format string returns the time in a long format, which typically includes hours, minutes, seconds, and the AM/PM designator if applicable. Example:
DECLARE @time TIME = '14:30:00';
SELECT FORMAT(@time, 'T') AS LongTime;
This will return the time formatted in a long time style, such as "2:30:00 PM" or "14:30:00" depending on your locale settings.
Complete Example
Here’s an example that demonstrates both:
DECLARE @datetime DATETIME = '2023-10-05 14:30:00';

SELECT 
    FORMAT(@datetime, 'D') AS LongDate,
    FORMAT(@datetime, 'T') AS LongTime;
Output Explanation
- The first result would give you the long date, e.g., "Thursday, October 5, 2023". - The second result would provide the long time, e.g., "2:30:00 PM".
Important Notes
1. Locale and Culture: The output of the FORMAT function can vary based on the language and locale settings of the SQL Server session. You can specify a culture explicitly as a third parameter in the FORMAT function, e.g., FORMAT(@datetime, 'D', 'en-US'). 2. Performance Consideration: The FORMAT function can be slower than other date formatting functions, especially on large datasets, so use it judiciously in performance-critical applications. By understanding how to use the FORMAT function with 'D' and 'T', you can effectively control how date and time values are represented in your SQL Server queries.