【问题标题】:convert DD-MM-YYYY to datetype in TSQL [duplicate]在 SQL 中将 DD-MM-YYYY 转换为日期时间 [重复]
【发布时间】:2020-05-19 11:55:03
【问题描述】:

我有一个格式为

的日期(实际上是一个字符串)

DD-MM-YYYY 00:00:00

我想要它的日期部分(我不在乎什么格式,我只需要它成为一个日期类型) 什么是最有效的方法?

【问题讨论】:

    标签: tsql azure-sql-database


    【解决方案1】:

    猜猜这就是诀窍:选择

    convert(date,left(enddate, charindex(' ',enddate)),103)
    

    【讨论】:

    • 这很完美。有趣的是,我不知道为什么,如果我使用格式 103 、 104 或 105,我总是在结果中得到“yyyy-mm-dd”格式。
    【解决方案2】:
    DECLARE @DTString   varchar(20) = '19-05-2020 09:30:00'
    
    SET @DTString   =   CONVERT(varchar(10), @DTString)     --  Get Datepart    (DD-MM-YYYY)
    
    -- There is no implicit conversion from astring to date.
    -- CONVERT won't work in that format. We need it in MM=DD-YYYY format.
    
    DECLARE @Day        varchar(02) 
    DECLARE @Month      varchar(02) 
    
    SET @Day        =   LEFT(@DTString, 2)                  --  Get the Day
    SET @Month      =   SUBSTRING(@DTString, 4, 2)          --  Get the Month
    
                    --  STUFF(String to be modified , start position    , number of chars to deleted    , String to insert)
    SET @DTString   =   STUFF(@DTString             , 1                 , 2                             , @Month)       --  Insert the Month at position 1, deleting 2 (the day  )
    SET @DTString   =   STUFF(@DTString             , 4                 , 2                             , @Day  )       --  Insert the Day   at position 4, deleting 2 (the month)
    
    SELECT @DTString    -- Here the transformation from DD-MM-YYYY to MM-DD-YYYY
    
    SELECT CONVERT(date, @DTString) -- Now we can convert
    

    【讨论】:

      猜你喜欢
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多