Search code examples
sqlsql-server-2005dateadd

T-SQL 2005: Add Date and Time


I have two fields which are both Datetime type:

Date = '2011-1-01 00:00:00.000'
Time = '1900-01-01 3:31:19.000'

The '1900-01-01' is the default value so I am interested only in the time part (3:31:19.000).

All what I want is to combine Date and time together. So, for this example i want a query which would give me the result:

Combined = '2011-1-01 3:31:19.000'

I am using T-SQL 2005.


Solution

  • If you want a string-less option, you can stack DATEADD/DATEPART operators together...

    DECLARE @Date DATETIME = '2011-1-01 00:00:00.000'
    , @Time DATETIME = '1900-01-01 3:31:19.000'
    
    SELECT DATEADD(hh, DATEPART(hh, @Time), DATEADD(mi, DATEPART(mi, @Time), @Date)) --and so on
    

    Results in 2011-01-01 03:31:00.000