Games
Problems
Go Pro!

# Seconds, Minutes, and Hours

Reference > Science > Technology > Beginner Programming Tips

I suspect every young computer programmer has dreamed, at one time or another, about creating the next amazing computer game. The fact is, it's a dream that is realized by a very very small percentage of programmers. But we all have to give it a shot, right? One of the common things you'll need to do is to take an elapsed time in seconds and put it into a format that your game player can read. After all, the player doesn't want to see that he took 12752 seconds to complete the level, right? He wants to know that it took him 3 hours, 32 minutes, and 32 seconds.

Now, how did I come up with that? Easy. I have a little function that converts seconds into other units. Let's take a look at it.

Function FormatTime(TimeElapsed As Integer) As
String
Dim Seconds As Integer
Dim Minutes As Integer
Dim Hours As Integer

'Find The Seconds
Seconds = TimeElapsed Mod 60

'Find The Minutes
Minutes = (TimeElapsed \ 60) Mod 60

'Find The Hours
Hours = (TimeElapsed \ 3600)

'Format The Time
If Hours > 0 Then
FormatTime = Format(Hours,"00") & ":"
End If
FormatTime = Format(Hours, "00")  & ":"
FormatTime = FormatTime & Format(Minutes,
"00") & ":"
FormatTime = FormatTime & Format(Seconds,
"00")
End Function

Let's take a closer look at this. First, I used the Modoperation to get the seconds. "Mod" finds the remainder when one number is divided by another. In this case, when we divide our time elapsed by 60 (one minute), our remainder is the number of seconds left over.

Then I did a similar process to find the minutes, only this time I had to divide the number of seconds by 60 to get the total number of minutes. Again, I used the Mod operator to find the remainder (in this case, the number of leftover minutes).

Finally, the number of hours is the number of seconds divided by 3600. Once again, I used Integer division ('\' instead of '/') because we don't want fractional hours.

The last step of the process is putting the values together in a string, using the Format function to get the right number of digits in each section.

Of course, there are probably other ways you might want to format your time, and that's what the Other Scenarios section of the page explores.

## Questions

1.
How would your function change if you wanted to display hours only if the time was greater than sixty minutes?
2.
How would your function change if you wanted to display minutes only if the time was greater than sixty seconds?
3.
Rewrite the function to handle the number of days, in addition to minutes, seconds, and hours. Assign this reference page Parsing a Comma-Separated List Handling Plurals and Singulars   Like us on Facebook to get updates about new resources