Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datetime to nvarchar but keep format

I am returning either a DATETIME or the NVARCHAR = 'MULTIPLE' depending on whether or not an action has been performed more than one time.

So I am trying to store the DATETIME in its normal format '2012-10-23 13:59:47.000' but as an NVARCHAR. SQL wants to make it 'Oct 23 2012 12:40PM' How can I do this?

Right now I am doing:

CAST(r.Date_And_Time) AS NVARCHAR(30))
like image 575
gooddadmike Avatar asked Dec 07 '12 23:12

gooddadmike


People also ask

Can we convert datetime to VARCHAR in SQL?

We can convert the DATETIME value to VARCHAR value in SQL server using the CONVERT function. Convert function has three arguments. Let us convert a DATETIME value into VARCHAR with different date styles. And that's how to convert DATETIME value to VARCHAR value in SQL Server!

How change date format in SQL?

You can specify the format of the dates in your statements using CONVERT and FORMAT. For example: select convert(varchar(max), DateColumn, 13), format(DateColumn, 'dd-MMM-yyyy')


2 Answers

Use CONVERT. It has format parameter.

CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

CONVERT(NVARCHAR(23), r.Date_And_Time, 121)

https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

like image 33
Anri Avatar answered Sep 22 '22 05:09

Anri


Declare @CreatedDate datetime
Select @CreatedDate='20121210'
Select CONVERT(VARCHAR,@createdDate, 21)
like image 97
bummi Avatar answered Sep 18 '22 05:09

bummi