Home »

Format DateTime in SQL

In SQL Server, when we want to format DATETIME value, we can use CAST or CONVERT function to convert DATETIME to VARCHAR with a specific format.
The different between two function is:
When you use CAST, it change the DATETIME value to the type of data that you specified
For example:
SELECT CAST(GETDATE() AS VARCHAR(23))
--RETURNS 'Jan  1 2011 10:48PM'
But when you use CONVERT function, you can change the date format
SELECT CONVERT(VARCHAR(23), GETDATE(), 103)
--RETURNS 01/01/2011
103 here is the default format style

Run the below code in SQL and you will find out all the default format available
DECLARE @i INT,
 @dt DATETIME
SET @i = 0
SET @dt = '2010-12-31 14:05:06.123'
WHILE @i < 150
BEGIN
 BEGIN TRY
  PRINT (CONVERT(VARCHAR, @i) + ' : ' + CONVERT (VARCHAR, @dt, @i))
  SET @i = @i + 1
 END TRY
 BEGIN CATCH
  SET @i = @i + 1
 END CATCH
END
You can change the value of @dt or @i to match your condition, maybe there will be more formats in the future, so you must change @i to 1000 to display them all for example xDxDxD.

Here is all the default formats available. I use '2010-12-31 14:05:06.123' for the date
Format StyleResult
0Dec 31 2010 2:05PM
112/31/10
210.12.31
331/12/10
431.12.10
531-12-10
631 Dec 10
7Dec 31, 10
814:05:06
9Dec 31 2010 2:05:06:123PM
1012-31-10
1110/12/31
12101231
1331 Dec 2010 14:05:06:123
1414:05:06:123
202010-12-31 14:05:06
212010-12-31 14:05:06.123
2212/31/10 2:05:06 PM
232010-12-31
2414:05:06
252010-12-31 14:05:06.123
100Dec 31 2010 2:05PM
10112/31/2010
1022010.12.31
10331/12/2010
10431.12.2010
10531-12-2010
10631 Dec 2010
107Dec 31, 2010
10814:05:06
109Dec 31 2010 2:05:06:123PM
11012-31-2010
1112010/12/31
11220101231
11331 Dec 2010 14:05:06:123
11414:05:06:123
1202010-12-31 14:05:06
1212010-12-31 14:05:06.123
1262010-12-31T14:05:06.123
1272010-12-31T14:05:06.123
13025 ???? 1432 2:05:06:123PM
13125/01/1432 2:05:06:123PM

Hope this entry help you!
If you found any mistake or error in this entry, please let me know. I'll try to fix that a.s.a.p.
Any solution is highly appreciated!
-Share2Learn-

1 comment:

  1. convert string to datetime and vice-versa is a time-consuming work. It can slow down your application when the database gets bigger. Just use it when you really-really need it. In most cases, you can handle DateTime.

    ReplyDelete