2

I've created a function for converting minutes (smallint) to time (varchar(5)), like 58 -> 00:58.

set QUOTED_IDENTIFIER ON

GO
Create FUNCTION [dbo].[IntToMinutes]
(
    @m smallint
)
RETURNS nvarchar(5)
AS
BEGIN
    DECLARE @c nvarchar(5)
     SET @c = CAST((@m / 60) as varchar(2)) + ':' + CAST((@m % 60) as varchar(2))
     RETURN @c
END

The problem is when there are less than 10 minutes in time, like 9. The result of this function is 0:9. I want that the format is 00:09.

How can I do that?

4 Answers 4

7
Create FUNCTION [dbo].[IntToMinutes]
(
    @m smallint 
)  
RETURNS nvarchar(5)
AS  
BEGIN
    DECLARE @c datetime
    select @c = dateadd(mi,@m,'00:00')       
    RETURN convert(nvarchar(5), @c, 108)   
END
1
  • This will not work for values larger then minutes for a day.. (even if you will convert it to 'int') Oct 15, 2013 at 8:17
1
declare @m smallint
declare @d varchar(10)

set @m = 9

DECLARE @c nvarchar(5)
SET @c = CAST((@m / 60) as varchar(2)) + ':' + CAST((@m % 60) as varchar(2))
set @d = Convert(varchar,cast(@c as datetime), 108)
set @c = LEFT(@d,5)
select @c

This works only for numbers between 0 and 1439, but it's fine for 24 hours. You can skip variable declaration @d and do that inline.

0

Pad the two (sub)strings with leading zeroes, then take the rightmost two characters returned:

CREATE FUNCTION [dbo].[IntToMinutes] 
( 
    @m smallint  
)   
RETURNS nvarchar(5) 
AS   
BEGIN 
    DECLARE @c nvarchar(5) 

    SET @c = RIGHT('0' + CAST((@m / 60) as varchar(2)), 2)
     + ':'
     + RIGHT('0' + CAST((@m % 60) as varchar(2)), 2)

     RETURN @c 
END

Note, of course, that this doesn't work so well once you get past 5999 minutes. If that's a problem, just make things a bit bigger/longer.

0
CREATE FUNCTION [dbo].[IntToMinutes]
(
    @m int
)
RETURNS nvarchar(20)
AS  
BEGIN

    DECLARE @c datetime
    DECLARE @c1 datetime
    SELECT @c =dateadd(mi,0,'00:00')              
    select @c1 = dateadd(mi,@m,'00:00')         

     return CONVERT(varchar(10),DATEDIFF(hh, @c, @c1) ) + ':' +
     CONVERT(varchar(10),DATEDIFF(mi,DATEADD(hh,DATEDIFF(hh, @c, @c1),@c),@c1) )
    end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.