Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: float number to hours format

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

Examples:

  • 1.5 -> 01:30
  • 9.8 -> 09:48
  • 35.25 -> 35:15

Thanks a lot.

like image 910
maxy56 Avatar asked May 19 '11 17:05

maxy56


People also ask

How do you format time in SQL?

SQL Server comes with the following data types for storing a date or a date/time value in the database: DATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS. SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS.

How do I show time in 24 hour format in SQL?

Use capital letter 'HH:mm:ss' for 24 hour date time format.


2 Answers

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);
like image 156
Yuck Avatar answered Nov 15 '22 16:11

Yuck


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).

like image 28
WReach Avatar answered Nov 15 '22 17:11

WReach