简体   繁体   中英

Convert days to hours in HHH:MM:SS Format (Nvarchar)

I have a table where i need to convert for example 2.6 days or 5 days, 3.2 days etc to hours. Since it is above 24 hours format i know i need to convert to nvarchar. I searched many forums and i cannot see exactly how can i do specifically this, i think i have to convert this days to seconds and then from seconds to nvarchar format. does anyone have any idea?

Thx all:)

You seem to think you need to use nvarchar. But that is not necessarily the case. If you can store your hours as decimal. The solution is simple

hours = days * 24

If you want to break it down to hours minutes and seconds you need to convert it to seconds. There are 24 hours in a day, 60 minutes in an hour and 60 seconds in a minute.

seconds = days * 24 * 60 * 60 

Once you have the seconds you can use the division operator (/) togheter with the modulo operator (%). If you store your days as decimal (3,1) you will not have to worry about seconds, because the resolution is too low.

select 
 days
 ,CAST(days * 24 * 60 * 60 as int) as totalseconds --days converted to full seconds
 ,CAST(days * 24 * 60 as int) as totalminutes --days converted to full minutes
 ,CAST(days * 24  as int) as totalfullhours --days converted to full hours
 ,CAST(days * 24 * 60 as int) % 60 as remainingminutes -- since the row above contains full hours, we need to find out how many minutes are in the split hours f ex 0.2 hours
 ,CAST(days * 24 * 60 * 60 as int) % 60 as remainingseconds -- this will always be 0 because of your precision
from YourTable

If you still want the result as a single string column (HH::mm) it will will be

select 
     CAST(CAST(days * 24  as int) as varchar(10)) + ':' + RIGHT('0'+CAST(CAST(days * 24 * 60 as int) % 60 as varchar(10)),2) 
    from YourTable

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