开发者

SQL: float number to hours format

Is there a easy way to format a float number in hours in Ms SQL server 2008?

Examples:

Thanks a lot.


I like this question!

DECLARE @input float = 1.5;

DECLARE @hour int = FLOOR(@input);
DECLARE @minutes int = (SELECT (@input - FLOOR(@input)) * 60);

SELECT RIGHT('00' + CONVERT(varchar(2), @hour), 2) + ':' + RIGHT('00' + CONVERT(varchar(2), @minutes), 2);


SELECT SUBSTRING(CONVERT(NVARCHAR, DATEADD(MINUTE, 1.5*60, ''), 108), 1, 5)

This works by:

  • starting from the "zero" date

  • adding 1.5 x 60 minutes (i.e. 1.5 hours)

  • formatting the result as a time, hh:mm:ss (i.e. format "108")

  • trimming off the seconds part

It is necessary to use 1.5 x 60 minutes instead of 1.5 hours as the DATEADD function truncates the offset to the nearest integer. If you want high-resolution offsets, you can use SECOND instead, suitable scaled (e.g. hours * 60 * 60).


Sure. Easy, but not exactly...straightforward:

declare @hours float 
set     @hours = -9.8

select substring('-  ',2+convert(int,sign(@hours)),1)                                        -- sign
     + right('00' + convert(varchar,                       floor(abs(@hours)))         , 2 ) -- hours component
     + ':'                                                                                   -- delimiter
     + right('00' + convert(varchar,round( 60*(abs(@hours)-floor(abs(@hours))) , 0 ) ) , 2 ) -- minutes

Another option that will give the correct result. You might need to tweak it to round minutes and to ensure that both fields are 2 digits wide.

declare @hours float 
set     @hours = -9.8

select       convert(varchar, datediff(minute,dateadd(minute,@hours*60,convert(datetime,'')),'') / 60 )
     + ':' + convert(varchar, datediff(minute,dateadd(minute,@hours*60,convert(datetime,'')),'') % 60 ) 


WITH m AS
  SELECT Minutes = CAST(@hours * 60 AS int)
)
SELECT CAST(Minutes / 60 AS varchar) + ':' + RIGHT(100 + Minutes % 60, 2)
FROM m


select dateadd(MINUTE, cast((8.18 % 1) * 60 as int), dateadd(hour, cast(8.18 as int), convert(varchar(10), getdate(), 10)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜