How to convert a datetime to string in T-SQL

前端 未结 9 1355
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 03:19

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

9条回答
  •  自闭症患者
    2020-12-13 03:59

    In addition to the CAST and CONVERT functions in the previous answers, if you are using SQL Server 2012 and above you use the FORMAT function to convert a DATETIME based type to a string.

    To convert back, use the opposite PARSE or TRYPARSE functions.

    The formatting styles are based on .NET (similar to the string formatting options of the ToString() method) and has the advantage of being culture aware. eg.

    DECLARE @DateTime DATETIME2 = SYSDATETIME();
    DECLARE @StringResult1 NVARCHAR(100) = FORMAT(@DateTime, 'g') --without culture
    DECLARE @StringResult2 NVARCHAR(100) = FORMAT(@DateTime, 'g', 'en-gb') 
    SELECT @DateTime
    SELECT @StringResult1, @StringResult2
    SELECT PARSE(@StringResult1 AS DATETIME2)
    SELECT PARSE(@StringResult2 AS DATETIME2 USING 'en-gb')
    

    Results:

    2015-06-17 06:20:09.1320951
    6/17/2015 6:20 AM
    17/06/2015 06:20
    2015-06-17 06:20:00.0000000
    2015-06-17 06:20:00.0000000
    

提交回复
热议问题