Archive for the ‘SQL’ Category

Set the time for a SQL datetime

Thursday, September 16th, 2010

I spent about an hour attempting to google the best way of changing the time of a SQL datetime midquery. I would think this would be easy, and it kind of was, but finding the logic that led me to it was confoundingly difficult. So hopefully you other googlers out there will benefit from my experience. This is for SQL Server, but other versions of SQL will have similar functions available to them.

--We start with DateAdd which adds the specified time interval to a date
DateAdd(timeinterval, amountoftime, date)

--We combine this with DateDiff which gives you the difference in time between two dates. We can ask DateDiff to give us the number of days between the start of time (0) and our current time. Now we have days with no time, essentially zero'ing the time.
DateDiff(timeinterval, starttime, endtime)
DateDiff(dd, 0, mydatetime)

--Finally we combine the two statements. DateDiff gives us our days and DateAdd converts that back into a datetime.
DateAdd(anytimeinterval, 0, DateDiff(dd, 0, mydatetime))

--But what about actually setting the time? No problem, just change "anytimeinterval" and the 0 right after it to the time you want to add
DateAdd(hh, 9, DateDiff(dd, 0, mydatetime)) would add nine hours to the truncated time.