2

I'm using following line of code in SQL:

REPLACE(CONVERT(VARCHAR(11),getdate(),106), ' ','-') 

to convert given date to MMM-DD-YYYY format, this code is working perfectly fine if current date is more that 10th.

But I'm getting error when its tries to convert single digit date, e.g when I'm converting date 9 jan 2014. It is converted to Jan--9-2014.

Which is actually wrong as its contain one extra -.

Please help me to resolve this issue.

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
Abhijeet
  • 21
  • 1
  • 1
  • 2

7 Answers7

2

CONVERT DATE IN dd-mmm-yyyy FORMAT (Eg. 01-Jun-2018)

REPLACE(CONVERT(CHAR(11), DOB, 106),' ','-')  AS DOB
Code
  • 679
  • 5
  • 9
2

As of SQL Server 2012+, you can use FORMAT(value, format [, culture ])

Where the format param takes any valid standard format string or custom formatting string

Example:

SELECT FORMAT(GETDATE(), 'dd-MMM-yyyy')

Further Reading:

KyleMit
  • 30,350
  • 66
  • 462
  • 664
-1

Try this

SELECT CONVERT(varchar(11),getdate(),103) 

see this link for more details

ann
  • 576
  • 1
  • 10
  • 19
Ajay
  • 6,418
  • 18
  • 79
  • 130
-1

Try This.

select REPLACE(REPLACE(CONVERT(VARCHAR,getdate(),107), ' ','-'), ',','')
Janty
  • 1,708
  • 2
  • 15
  • 29
-1
select REPLACE(replace(cast(getDate() as varchar(11)), '  ', ' '), ' ','-')

returns correct result Jan-9-2014 on your fiddle

here is the fiddle

user1455836
  • 752
  • 6
  • 18
-1

How about this:

select REPLACE(REPLACE(REPLACE(cast(getDate() as varchar(11)),' ','{}'),'}{',''),'{}','-')

Output: Jan-9-2014

SQL Fiddle Demo

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
-1

What about

select left(DATEname(m,getdate()),3)+'-'+  
cast(DAY(getdate()) as varchar)+'-'+ 
CAST(year(getdate()) as varchar)

?

msi77
  • 1,602
  • 1
  • 11
  • 10