6

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.

1
  • yes i'm using sql server 2008 Commented Jul 18, 2013 at 13:16

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

4 Comments

"The datepart hour is not supported by date function dateadd for data type date." (or, from the documentation for DATEADD: "The return data type is the data type of the date argument, except for string literals")
it's giving this error : The datepart hour is not supported by date function dateadd for data type date.
@Damien_The_Unbeliever: arrrrgh! Of course - if it's a DATE, then it doesn't allow housr...... so you need to cast to DATE first to get zero time, then back to DATETIME so you can add hours..... thanks for pointing this out!
SO is so cool due to guys like you @Damien_The_Unbeliever and @marc_s
3

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.

2 Comments

+1 extra-smart - just not very intuitive and maintainable over time :-) Who'll figure this out in 6, 12 months from now? Better leave a good comment in your code! :-)
@marc_s - The first, second or third time you encounter it, it may not be too intuitive. But since it's my "go-to" pattern for date/time manipulation, anyone who's worked with me for any amount of time quickly learns the pattern.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.