In Microsoft SQL Server, there are several types for handling dates and times.

For this post, we will not deal with DateTimeOffset, as that has additional implications.

For DateTime and DateTime2, the date and time components are contained within the type.

declare @DateTime  datetime = getdate()
declare @DateTime2 datetime2 = getdate()

select @DateTime [DateTime], @DateTime2 [DateTime2]

If we run this, we will get the following:

datetimeresults

The date and time types, however, are specialized.

declare @Date date=getdate()
declare @Time time = getdate()

select @Date [Date], @Time [Time]

This returns the following:

dateandtimeresult

The situation may arise when you want to combine these date and time objects into a DateTime.

This is achieved as follows:

SELECT CAST(@Date AS DATETIME) + CAST(@Time AS DATETIME)

This will return the following:

dateTimeResult

The complete script is as follows:

declare @DateTime  datetime = getdate()
declare @DateTime2 datetime2 = getdate()

select @DateTime [DateTime], @DateTime2 [DateTime2]

declare @Date date=getdate()
declare @Time time = getdate()

select @Date [Date], @Time [Time]

SELECT CAST(@Date AS DATETIME2) + CAST(@Time AS DATETIME2) [DateTime]

Note: this solution will not work for a DateTime2. We will look at that in the next post.

TLDR

You can combine a SQL Server date and time into a DateTime using casting and addition.

Happy hacking!