13 Mar 2012

Seconds, Minutes, and Hours

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 Mod operation 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.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.