I\'m surprised not to be able to find this question here already.
I have a date time var and I want to convert it to a string so that I can append it to another stri
There are 3 different methods depending on what I is my requirement and which version I am using.
Here are the methods..
1) Using Convert
DECLARE @DateTime DATETIME = GETDATE();
--Using Convert
SELECT
CONVERT(NVARCHAR, @DateTime,120) AS 'myDateTime'
,CONVERT(NVARCHAR(10), @DateTime, 120) AS 'myDate'
,RIGHT(CONVERT(NVARCHAR, @DateTime, 120),8) AS 'myTime'
2) Using Cast (SQL Server 2008 and beyond)
SELECT
CAST(@DateTime AS DATETIME2) AS 'myDateTime'
,CAST(@DateTime AS DATETIME2(3)) AS 'myDateTimeWithPrecision'
,CAST(@DateTime AS DATE) AS 'myDate'
,CAST(@DateTime AS TIME) AS 'myTime'
,CAST(@DateTime AS TIME(3)) AS 'myTimeWithPrecision'
3) Using Fixed-length character data type
DECLARE @myDateTime NVARCHAR(20) = CONVERT(NVARCHAR, @DateTime, 120);
DECLARE @myDate NVARCHAR(10) = CONVERT(NVARCHAR, @DateTime, 120);
SELECT
@myDateTime AS 'myDateTime'
,@myDate AS 'myDate'
You can use the convert
statement in Microsoft SQL Server to convert a date to a string. An example of the syntax used would be:
SELECT convert(varchar(20), getdate(), 120)
The above would return the current date and time in a string with the format of YYYY-MM-DD HH:MM:SS
in 24 hour clock.
You can change the number at the end of the statement to one of many which will change the returned strings format. A list of these codes can be found on the MSDN in the CAST and CONVERT reference section.
There are many different ways to convert a datetime
to a string. Here is one way:
SELECT convert(varchar(25), getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm
See Demo
Here is a website that has a list of all of the conversions:
How to Format datetime & date in SQL Server
Try below :
DECLARE @myDateTime DATETIME
SET @myDateTime = '2013-02-02'
-- Convert to string now
SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)
Check CAST and CONVERT syntax of t-sql:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
The following query will get the current datetime and convert into string. with the following format yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar(25), getdate(), 120)