Convert Time To Decimal (SQL)

I was following the SQL list and came across a post from Jim Gotwald where he showed his solution to convert a time string into a decimal value (ex: ’10:30′ to 10.5).

So I decided to write a custom function where you can either pass a complete date as a string or just the time and it will return a float value representing the time in decimal.

You may call the function like this:

select dbo.timeToDecimal(cast(getDate()) as varchar(20))
select dbo.timeToDecimal(’2008-06-18 10:35:43′)
select dbo.timeToDecimal(’06/18/2009 10:22:00′)
select dbo.timeToDecimal(’10:42′)

Here is the function:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        Ricardo Parente
-- Create date: 2009-06-18
-- Description:    I convert a time string to decimal
-- Parameter: datetime string (varchar) or just a time string
-- =============================================
CREATE FUNCTION dbo.timeToDecimal
(
@timeToConvert varchar(25)
)
RETURNS float
AS
BEGIN
DECLARE @Result float
DECLARE @t varchar(5)
SET @t = cast(datepart(hh,@timeToConvert) as varchar(2)) + ':' + cast(datepart(n,@timeToConvert) as varchar(2))
SET @Result = CAST(DATEDIFF(N, '00:00', @t) AS FLOAT)/60
RETURN @Result
END
GO

Bookmark and Share
Jun 18th, 2009 | Posted in Database, SQL
  1. Aug 2nd, 2009 at 02:42 | #1

    This is pretty good. I have been using the MySQL date_format() function. It is nice to know how to return that value in decimal.

    Thanks!

  2. anon
    Apr 4th, 2012 at 06:00 | #2

    works

  3. Apr 19th, 2012 at 16:24 | #3

    vc é foda, AMEI sua função !

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>