Date and Time Conversions Using SQL Server
Date and Time Conversions Using SQL Server
com/) MENU
Problem
There are many instances when dates and times don't show up at your doorstep in the format you'd like it to
be, nor does the output of a query fit the needs of the people viewing it. One option is to format the data in
the application itself. Another option is to use the built-in functions SQL Server provides to format the date
string for you.
Solution
SQL Server provides a number of options you can use for formatting a date/time string in SQL queries and
stored procedures either from an input file (Excel, CSV, etc.) or a date column (datetime, datetime2,
smalldatetime, etc.) from a table. One of the first considerations is the actual date/time value needed. The
most common is the current date/time using getdate() (/sqlservertip/6817/sql-current-date/). This
provides the current date and time according to the server providing the date and time. If a universal
date/time (UTC) is needed, then getutcdate() (/sqlservertip/6817/sql-current-date/) should be used. To
change the format of the date, you convert the requested date to a string and specify the format number
corresponding to the format needed.
Below is a list of SQL date formats and an example of the output. The date used for all of these examples is
"2022-12-30 00:38:54.840".
107 select convert(varchar, getdate(), 107) Mon dd, yyyy Dec 30, 2022
0 select convert(varchar, getdate(), 0) Mon dd yyyy hh:mm AM/PM Dec 30 2022 12:38AM
9 select convert(varchar, getdate(), 9) Mon dd yyyy hh:mm:ss:nnn AM/PM Dec 30 2022 12:38:54:840AM
13 select convert(varchar, getdate(), 13) dd Mon yyyy hh:mm:ss:nnn AM/PM 30 Dec 2022 00:38:54:840AM
100 select convert(varchar, getdate(), 100) Mon dd yyyy hh:mm AM/PM Dec 30 2022 12:38AM
109 select convert(varchar, getdate(), 109) Mon dd yyyy hh:mm:ss:nnn AM/PM Dec 30 2022 12:38:54:840AM
113 select convert(varchar, getdate(), 113) dd Mon yyyy hh:mm:ss:nnn 30 Dec 2022 00:38:54:840
131 select convert(nvarchar, getdate(), 131) dd mmm yyyy hh:mi:ss:nnn AM/PM 10/12/1444 12:38:54:840AM
You can also format the date or time without dividing characters, as well as concatenate the date and time
string:
If you want to get a list of all valid date and time formats, you could use the code below and change the
@date to GETDATE() or any other date you want to use. This will output just the valid formats.