Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine date and time in SQL Server in SELECT query

I have From date in my table but I want to add fix time to it

I'm trying like this

select cast(FromDate as date) + cast('18:00:00' as time(3)) as StartDT 
from WsWmpLeaveReason

but this is causing an error:

Operand data type date is invalid for add operator.

like image 527
Kulmi Rajmal Avatar asked Jul 18 '13 13:07

Kulmi Rajmal


People also ask

Does Getdate () include time?

GETDATE returns the current date and time in the current session time zone (UTC by default). It returns the start date or time of the current statement, even when it is within a transaction block.


3 Answers

Use DATEADD:

SELECT
   DATEADD(HOUR, 18, CAST(CAST(FromDate AS DATE) AS DATETIME)) as StartDT 
FROM
   WsWmpLeaveReason

See the freely available, comprehensive SQL Server Books Online documentation for more details on DATEADD and its options

like image 158
marc_s Avatar answered Oct 10 '22 04:10

marc_s


Just as a different take on things, I'll wheel out my favourite DATEADD/DATEDIFF trick once again:

select DATEADD(day,DATEDIFF(day,'20010101',FromDate),'2001-01-01T18:00:00')
from WsWmpLeaveReason

This works by computing the (integral) number of days since 1st January 2001 to FromDate, and then adding that same number of (integral) days onto 18:00 on 1st January 2001. This, by deduction, must produce a date that has the same date as FromDate, but with the time portion fixed to 18:00.

like image 3
Damien_The_Unbeliever Avatar answered Oct 10 '22 05:10

Damien_The_Unbeliever


I would just use datetime and addition:

select cast(cast(FromDate as date) as datetime) + cast('18:00:00' as time(3)) as StartDT 
from WsWmpLeaveReason;

If FromDate is already lacking a time component, you can just do:

select cast(FromDate as datetime) + cast('18:00:00' as time(3)) as StartDT 
from WsWmpLeaveReason;

You can add a time to a datetime, but not to a date.

like image 1
Gordon Linoff Avatar answered Oct 10 '22 05:10

Gordon Linoff