Hours difference between time in sql server

自闭症网瘾萝莉.ら 提交于 2019-12-13 03:37:23

问题


I am trying to get the hours between the two dates using DATEDIFF(HOUR, FromTime, ToTime) but when the time is 00:00:00. And the I got the negative and wrong hours.

Code Below:

select FromTime, ToTime, datepart(HH, FromTime) as fromtimehours,
datepart(HH, ToTime) as totimehours, 
DATEDIFF(HOUR, FromTime, ToTime) as totalhours
from table

回答1:


How about a case statement to catch if it is a negative value and then calculate properly:

CASE WHEN DATEDIFF(HOUR, FromTime, ToTime) < 0 
THEN 24 - DATEPART(hour, FromTime) + DATEPART(hour, ToTime)
ELSE DATEDIFF(HOUR, FromTime, ToTime) 
END AS TotalHours


来源:https://stackoverflow.com/questions/25042287/hours-difference-between-time-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!