Reputation: 725
Hi I am working with SQL 2014 and I need to convert the following 2 date formats:
12/31/18 - Varchar
12/31/2018 - Varchar
to this format final format
December 31,2018 Varchar
I know that use varchar is not the correct. any suggestion?
Upvotes: 1
Views: 76
Reputation: 5653
You can try the following query also using
create table DateValue (DateVal varchar(10))
insert into DateValue values
('12/31/18'),
('12/31/2018'),
('01/31/18'),
('01/31/2018')
Select
DateName( month , DateAdd( month , DATEPART(MONTH, DateVal) , 0 ) - 1 ) + ' ' +
Cast(DATEPART(dd, DateVal) as Varchar) + ', ' +
+ Cast (DATEPART(YYYY, DateVal) as Varchar) as VarcharDate
from DateValue
The output will be as shown below.
VarcharDate
----------------
December 31, 2018
December 31, 2018
January 31, 2018
January 31, 2018
This query will also run in lower version of SQL Server where format()
is not available.
Upvotes: 2
Reputation: 38199
Try to use:
DECLARE @f varchar(50) = '12/31/18'
SELECT FORMAT(CAST(@f AS DATETIME), N'MMMM dd, yyyy')
OUTPUT:
December 31, 2018
And your second variant:
DECLARE @f varchar(50) = '12/31/2018'
SELECT FORMAT(CAST(@f AS DATETIME), N'MMMM dd, yyyy')
OUTPUT:
December 31, 2018
Upvotes: 6