Pablo Gûereca
Pablo Gûereca

Reputation: 725

More date format conversion SQL

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

Answers (2)

Suraj Kumar
Suraj Kumar

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.

Live Demo

Upvotes: 2

StepUp
StepUp

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

Related Questions