简体   繁体   中英

how to show float numbers in Hours, Day, Minute, Second in SQL Server

I have a simple record in table below:

Depart_dt                    Arrived_dt
10/1/2013 6:15:00 AM         10/1/2013 7:25:00 AM    

Based on my calculation, it is 1 hour and 10 min. Thanks to VKP, I used the datediff function as below:

Select 
Dateiff (DD, depart_dt, arrived_dt) as day,
Dateiff (HH, depart_dt, arrived_dt) as hour,
Dateiff (Minute, depart_dt, arrived_dt) as min,
Date if (second, depart_dt, arrived_dt) as second 
from temp

However, my result looks funny with the minute and second columns

Day   Hour   Min   Second 
0     1      70    4200

The hour appears correct but I am not sure how it comes to 70 in min column and 4200 in second column?

sorry guys, I was wrong. Yes, 70 min is correct because that is 1 hour and 10 min. Please disregard this

You can just use DATEDIFF to get the difference as an integer.

select item, 
datediff(dd, start_dt, end_dt) as total_days,
datediff(hh, start_dt, end_dt) as total_hours,
datediff(minute, start_dt, end_dt) as total_minutes,
datediff(second, start_dt, end_dt) as total_seconds
from yourtable

When using datediff you'll have to understand what it does. The name is quite confusing, because it doesn't actually calculate date differences, but according the documentation : "Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate."

That means that for example datediff hour for 06:15 and 07:00 is 1 hour.

You'll probably want something like this:

DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])/86400 as Days,
((DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])%86400)/3600) as Hours,
(((DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])%86400)%3600)/60) as Minutes,
(((DATEDIFF(SECOND, [Depart_dt], [Arrived_dt])%86400)%3600)%60) as Seconds

This calculates the amounts in full days / hours etc so number of hours will never be 24 or more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM