How to add st, nd, rd & th to dates in SQL Server

Useful Microsoft SQL Server code snippets.
Post Reply
Z12
Site Admin
Posts: 20
Joined: Thu Sep 30 2021, 11:47
Location: UK
Contact:

How to add st, nd, rd & th to dates in SQL Server

Post by Z12 »

In this example we are getting the long date with the name of the day and the name of the month for example "Sunday 13th March 2022" and adding st, nd, rd or th as appripriate.

Code: Select all

SELECT @Date AS TheDate,  
	DATENAME(weekday, @Date) + ' ' + 
		CONVERT(VARCHAR(2), DATEPART(day, @Date)) + '' + 
		CASE WHEN DATEPART(day, @Date) IN (1,21,31) THEN 'st'
			WHEN DATEPART(day, @Date) IN (2, 22) THEN 'nd'
			WHEN DATEPART(day, @Date) IN (3, 23) THEN 'rd'
			ELSE 'th' END + ' ' +
		DATENAME(month, @Date) + ' ' + 
		CONVERT(VARCHAR(10), DATEPART(year, @Date)) AS TheLongDate
If you find Z12 Web Tools useful and would like to show your appreciation...
Why not Buy Me A Coffee to say: Thank You!


Post Reply