Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql date convert to string format

Tags:

sql-server

How can I convert GETDATE() into a string like so: '2010-10-15'

-rod.

like image 424
Rod Avatar asked Oct 15 '10 15:10

Rod


People also ask

How do I convert a date to a string in SQL?

In order to convert a DateTime to a string, we can use CONVERT() and CAST() function. These functions are used to converts a value(of any datatype) into a specified datatype.

How do I change the 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

SELECT CONVERT(VARCHAR(10), GETDATE(), 120)

By setting the varchar length, you can effectively truncate unwanted portions of the DateTime

CAST and CONVERT (Transact-SQL)

like image 187
Brad Avatar answered Sep 28 '22 08:09

Brad


Here a complext way to do it:

Select Convert(char(4),DATEPART(yy,GetDate())) + '-' + convert(char(2),DATEPART(mm,GetDate())) + '-' + Convert(char(2),DATEPART(dd,GetDate()))

An easier way is:

Select Convert(VARCHAR(10), GetDate(), 120)

You might want to take a look at the T-SQL Convert function. It allows you to format dates in many pre-defined ways:

http://msdn.microsoft.com/en-us/library/ms187928.aspx
like image 44
Randy Minder Avatar answered Sep 28 '22 08:09

Randy Minder