Editorials

Formatting Dates in SQL Server

Date Formatting is very helpful. While it is not always the preferred thing to do in your database, there is native support built in. SQL Server allows you to convert or cast a date into a string value, and during the casting to provide a formatting method.

The formatting is specified by providing an integer value. Following is a query demonstrating the formatting natively supported in SQL Server at this time.

;WITH Sequence (Number)

AS

(

SELECT TOP (14)

ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY ID) AS Number

FROM SYSOBJECTS

)

SELECT

Number as TwoDigitYearFormat

,CONVERT(VARCHAR(20), GETDATE(), Number) AS TwoYearFormatted

,Number + 100 as FourDigitYearFormat

,CONVERT(VARCHAR(20), GETDATE(), Number + 100) AS FourYearFormatted

FROM Sequence

Executing the query results in the following output.

TwoDigitYearFormat

TwoYearFormatted

FourDigitYearFormat

FourYearFormatted

1

03/18/15

101

03/18/2015

2

15.03.18

102

2015.03.18

3

18/03/15

103

18/03/2015

4

18.03.15

104

18.03.2015

5

18-03-15

105

18-03-2015

6

18 Mar 15

106

18 Mar 2015

7

Mar 18, 15

107

Mar 18, 2015

8

20:03:28

108

20:03:28

9

Mar 18 2015 8:03:28

109

Mar 18 2015 8:03:28

10

03-18-15

110

03-18-2015

11

15/03/18

111

2015/03/18

12

150318

112

20150318

13

18 Mar 2015 20:03:28

113

18 Mar 2015 20:03:28

14

20:03:28:923

114

20:03:28:923

I prefer the Dot Net formatting implementation. A DateTime data type can be converted to a string using the ToString() method. You can provide a string format in the ToString methods allowing you to specify each of the individual date components.

If you have a DateTime variable MyDate with the value “1/23/2015 01:23:04:461 PM” you could convert it to the string 23/jan/2015 13:23:04:461 by using the following format:

MyDate.ToString(“dd/MMM/yyyy HH:mm:ss:fff”)

I wish they supported the same kind of formatting in SQL Server. Perhaps that is a place for you to add a CLR function. Then you have a granular method to format any date without having to resort to a lot of DATEPART SQL functions, etc.

I know I’ve written on this before. I find the topic to still be fresh, as I often have people ask me how this kind of formatting may be done.

Do you have a TSQL function or CLR function you use for formatting dates in SQL? Share your idea in a comment or by Email to btaylor@sswug.org.

Cheers,

Ben