How to add time to DateTime in SQL

后端 未结 9 1992
一生所求
一生所求 2020-12-29 01:47

I\'m trying to add custom time to datetime in SQL Server 2008 R2.

Following is what I\'ve tried.

SELECT DATEADD(hh, 03, DATEADD(mi,         


        
相关标签:
9条回答
  • 2020-12-29 02:28

    Or try an alternate method using Time datatype:

    DECLARE @MyTime TIME = '03:30:00', @MyDay DATETIME = CAST(GETDATE() AS DATE)
    
    SELECT @MyDay+@MyTime
    
    0 讨论(0)
  • 2020-12-29 02:30

    The following is simple and works on SQL Server 2008 (SP3) and up:

    PRINT @@VERSION
    PRINT GETDATE()
    PRINT GETDATE() + '01:00:00'
    PRINT CONVERT(datetime,FLOOR(CONVERT(float,GETDATE()))) + '01:00:00'
    

    With output:

    Microsoft SQL Server 2008 (SP3) - 10.0.5500.0 (X64) 
    Mar 15 2017  6:17PM
    Mar 15 2017  7:17PM
    Mar 15 2017  1:00AM
    
    0 讨论(0)
  • 2020-12-29 02:30
    DECLARE @DDate      date        -- To store the current date
    DECLARE @DTime      time        -- To store the current time
    DECLARE @DateTime   datetime    -- To store the result of the concatenation
    ;
    SET @DDate      =   GETDATE()   -- Getting the current date
    SET @DTime      =   GETDATE()   -- Getting the current time
    
    
    
    SET @DateTime   =   CONVERT(datetime, CONVERT(varchar(19), LTRIM(@DDate) + ' ' + LTRIM(@DTime) ));
    ;
    /*
        1. LTRIM the date and time do an automatic conversion of both types to string.
        2. The inside CONVERT to varchar(19) is needed, because you cannot do a direct conversion to datetime
        3. Once the inside conversion is done, the second do the final conversion to datetime.
    */  
    
    -- The following select shows the initial variables and the result of the concatenation
    SELECT @DDate, @DTime, @DateTime
    
    0 讨论(0)
提交回复
热议问题