There are various versions of this sort of thing on the web but until today I couldn't find this thing exactly so I decided to write it myself.
CREATE FUNCTION fn_SecondsToWords (
@Seconds int)
RETURNS varchar(500)
AS
BEGIN
DECLARE @Words varchar(500)
SET @Words = ''
DECLARE @Minutes int
DECLARE @Hours int
DECLARE @Days int
-- less than a minute
IF @Seconds < 60
BEGIN
SET @Words = CAST(@Seconds AS VARCHAR(2)) + ' seconds'
END
-- between a minute and an hour
IF @Seconds BETWEEN 60 AND ((60*60)-1)
BEGIN
SET @Minutes = @Seconds / 60
SET @Seconds = @Seconds % 60
SET @Words = CAST(@Minutes AS VARCHAR(2)) + ' minute(s), '
+ CAST(@Seconds AS VARCHAR(2)) + ' seconds'
END
-- between an hour and a day
IF @Seconds BETWEEN 3600 AND 86399
BEGIN
SET @Hours = @Seconds / 3600
SET @Seconds = @Seconds % 3600
SET @Minutes = @Seconds / 60
SET @Seconds = @Seconds % 60
SET @Words = CAST(@Hours AS VARCHAR(2)) + ' hour(s), '
+ CAST(@Minutes AS VARCHAR(2)) + ' minute(s), '
+ CAST(@Seconds AS VARCHAR(2)) + ' seconds'
END
-- over a day
IF @Seconds >= 86400
BEGIN
SET @Days = @Seconds / 86400
SET @Seconds = @Seconds % 86400
SET @Hours = @Seconds / 3600
SET @Seconds = @Seconds % 3600
SET @Minutes = @Seconds / 60
SET @Seconds = @Seconds % 60
SET @Words = CAST(@Days AS VARCHAR(3)) + ' day(s), '
+ CAST(@Hours AS VARCHAR(2)) + ' hour(s), '
+ CAST(@Minutes AS VARCHAR(2)) + ' minute(s), '
+ CAST(@Seconds AS VARCHAR(2)) + ' seconds'
END
RETURN @Words
END
If you'd like some sort of an explanation as to how it works then here goes:
First job is to determine of the number of seconds is less than 60 because that's easy. Just show the number of seconds and concatenate the word ' second(s)' onto the end.
Next is to deal with anything between a minute and an hour. in terms of seconds that's 60 to 3600 except we're going to use 3599 so we're just dealing with seconds and minutes. The line that says SET @Minutes = @Seconds / 60 is calculating the number of minutes simply by dividing the number of seconds by 60.
The code SET @Seconds = @Seconds % 60 uses the MOD(%) function which is a funny by extremely helpful fella. MOD will return the remainder when you divide a number by another number.
For example, if we were dealing with 95 seconds, the line SET @Seconds = @Seconds % 60 divides 95 by 60 and returns the remainder which is of course 35.
So we've got the result of 95 DIVIDED BY 60 (1) and 95 MOD 60 (35) and that outputs 1 minute and 35 seconds (95 seconds).
The rest of the function simply expands on this premise to calculate hours and even days. You now have the tools to add weeks and years onto it or to convert it so that its converting minutes or miliseconds or whatever you want.
No comments:
Post a Comment