Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format a datetime to varchar with the format dd-MMM-yyyy?

I feel this should be a simple solution but I'm having trouble finding anything on it...

So: How do I get from a datetime to a varchar with the format dd-MMM-yyyy?

Eg: my_date --> '29-May-2012'

The closes I've managed to come is

convert(varchar(20),my_date,105) --> '29-05-2012'

Yes, I DO need to do this right in T-SQL.

like image 363
AR. Avatar asked May 30 '12 19:05

AR.


2 Answers

This format isn't natively supported, but from Build a cheat sheet for SQL Server date and time formats, the closest is probably:

SELECT REPLACE(CONVERT(CHAR(11), GETDATE(), 106), ' ', '-');

A previous version of this answer recommended FORMAT(), but I have since experimented and believe that's a bad idea at scale unless you just want all your queries to take twice as long.

like image 149
Aaron Bertrand Avatar answered Nov 15 '22 08:11

Aaron Bertrand


You could use:

SELECT replace(convert(char(11), getdate(), 113), ' ', '-')

or

SELECT replace(convert(char(11), getdate(), 106), ' ', '-')
like image 35
Taryn Avatar answered Nov 15 '22 08:11

Taryn