Is there a easy way to format a float number in hours in Ms SQL server 2008?
Examples:
Thanks a lot.
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.
Use capital letter 'HH:mm:ss' for 24 hour date time format.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With