Share via

date format in tsql

coool sweet 61 Reputation points
2021-05-12T15:53:50.023+00:00

hi

i have column values as ' wed, 7 Apr 2021 14:42:25', i need to convert it
as 2021-04-07 14:42:25.

how to do it?

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.


2 answers

Sort by: Most helpful
  1. EchoLiu-MSFT 14,626 Reputation points
    2021-05-13T03:16:02.537+00:00

    Hi @coool sweet ,

    Please refer to:

    CREATE TABLE #test(dates char(25))  
    INSERT INTO  #test VALUES('wed, 7 Apr 2021 14:42:25')  
      
    SELECT FORMAT(CAST(RIGHT(dates,LEN(dates)-CHARINDEX(',',dates)) as datetime2),'yyyy-MM-dd HH:mm:ss')  
    FROM #test  
    

    Output:

    2021-04-07 14:42:25  
    

    If you want to update the column, then:

    UPDATE #test  
    SET dates=FORMAT(CAST(RIGHT(dates,LEN(dates)-CHARINDEX(',',dates)) as datetime2),'yyyy-MM-dd HH:mm:ss')  
    FROM #test  
    

    If you have any question, please feel free to let me know.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Was this answer helpful?

    0 comments No comments

  2. Viorel 127K Reputation points
    2021-05-12T19:08:33.41+00:00

    If you want to convert a string column like ‘varchar(max)’, then try something like this:

    update t
    set MyColumn = convert(varchar(max), c, 120)
    from MyTable t
    cross apply (values (try_convert(datetime, substring(ltrim(MyColumn), 5, 100), 113))) d(c)
    where len(MyColumn) > 4 and  c is not null
    

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.