how to format getdate into YYYYMMDDHHmmSS

后端 未结 7 1502
春和景丽
春和景丽 2021-02-19 04:50

In SQL Server how do I format getdate() output into YYYYMMDDHHmmSS where HH is 24 hour format?

I\'ve got the YYYYMMDD

相关标签:
7条回答
  • 2021-02-19 05:23
    select CONVERT(nvarchar(8),getdate(),112) + 
    case when Len(CONVERT(nvarchar(2),DATEPART(HH,getdate()))) =1 then '0' + CONVERT(nvarchar(2),DATEPART(HH,getdate())) else CONVERT(nvarchar(2),DATEPART(HH,getdate())) end +
    case when Len( CONVERT(nvarchar(2),DATEPART(MI,getdate())) ) =1 then '0' + CONVERT(nvarchar(2),DATEPART(MI,getdate())) else CONVERT(nvarchar(2),DATEPART(MI,getdate())) end
    
    0 讨论(0)
  • 2021-02-19 05:31

    Try this:

    select CONVERT(varchar, GETDATE(), 120) e.g.

    2011-09-23 12:18:24 (yyyy-mm-dd hh:mi:ss (24h) ,ODBC canonical).

    Hth.

    0 讨论(0)
  • 2021-02-19 05:34

    Another option!

    SELECT CONVERT(nvarchar(8), GETDATE(),112) + 
       CONVERT(nvarchar(2),DATEPART(HH,GETDATE())) + 
       CONVERT(nvarchar(2),DATEPART(MI,GETDATE())) + 
       CONVERT(nvarchar(2),DATEPART(SS,GETDATE()));
    
    0 讨论(0)
  • 2021-02-19 05:34

    converting datetime that way requires more than one call to convert. Best use for this is in a function that returns a varchar.

    select CONVERT(varchar,GETDATE(),112) --YYYYMMDD
    select CONVERT(varchar,GETDATE(),108) --HH:MM:SS
    

    Put them together like so inside the function

    DECLARE @result as varchar(20)
    set @result = CONVERT(varchar,GETDATE(),112) + ' ' + CONVERT(varchar,GETDATE(),108)
    print @result
    

    20131220 13:15:50

    As Thinhbk posted you can use select CONVERT(varchar,getdate(),20) or select CONVERT(varchar,getdate(),120) to get quite close to what you want.

    0 讨论(0)
  • 2021-02-19 05:35
    select replace(
           replace(
           replace(convert(varchar(19), getdate(), 126),
           '-',''),
           'T',''),
           ':','')
    
    0 讨论(0)
  • 2021-02-19 05:42

    Just for anyone searching for this functionality that has SQL Server 2012 you can use the FORMAT function:

    SELECT FORMAT ( GETDATE(), 'yyyyMMddHHmmss') AS 'Custom DateTime'
    

    This allows any .NET format strings making it a useful new addition.

    0 讨论(0)
提交回复
热议问题