ddmmyyyy to sql datetime in SQL

后端 未结 6 1218
旧巷少年郎
旧巷少年郎 2020-12-21 03:48

I need to convert a nvarchar value to datetime in T-SQL. The value is in ddmmyyyy format, e.g. 23072009

I need t

相关标签:
6条回答
  • 2020-12-21 03:56

    Change VARCHAR (dd-mm-yyyy) to date (yyyy-mm-dd) in SQL Server.

    DECLARE @VarDate VARCHAR(10)
    SET @VarDate  = '22-02-1994'
    
    SELECT CONVERT(DATETIME, CONVERT(VARCHAR, CONVERT(DATE, @VarDate, 103), 102))
    
    0 讨论(0)
  • 2020-12-21 04:01

    Format 103 expects dd/mm/yyyy. (see here)

    I don't think you'll be able to do it using convert, as non of the convert options have that format.

    0 讨论(0)
  • 2020-12-21 04:06

    You can define custom function like this:

    CREATE FUNCTION [dbo].[GetCustomDate] (@customDateString NVARCHAR(MAX)) 
    RETURNS DATETIME
    AS
    BEGIN
    
        RETURN CONVERT(DATETIME, RIGHT(@customDateString, 4) + RIGHT(LEFT(@customDateString, 4), 2) + LEFT(@customDateString, 2))
    
    END
    0 讨论(0)
  • 2020-12-21 04:08

    You need to cast a string and not a int. Put some quotes:

    convert(datetime, '23072009', 103)
    

    And 103 gets the string like 'dd/mm/yyyy' and not 'ddmmyyyy'.

    0 讨论(0)
  • 2020-12-21 04:13

    The style 103 will accept strings with dd/mm/yyyy format. So your code should be

    declare @date varchar(8)
    set @date='23072009'
    select convert(datetime,stuff(stuff(@date,5,0,'/'),3,0,'/')  , 103) 
    
    0 讨论(0)
  • 2020-12-21 04:15

    Rebuild your format to yyyymmdd.

    declare @D varchar(8)
    set @D = '23072009'
    
    select cast(right(@D, 4)+substring(@D, 3, 2)+left(@D, 2) as datetime)
    
    0 讨论(0)
提交回复
热议问题