Date and Time Conversions Using SQL Server
Date and Time Conversions Using SQL Server
Server
By: Edgewood Solutions | Read Comments (28) | Related Tips: 1 | 2 | 3 | 4 | 5 | 6 | 7 | More > Dates
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 to format a date/time string. One
of the first considerations is the actual date/time needed. The most common is the
current date/time using getdate(). This provides the current date and time according to
the server providing the date and time. If a universal date/time is needed,
then getutcdate() 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 formats and an example of the output. The date used for all of these
examples is "2006-12-30 00:38:54.840".
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.