VB .NET - Add leading zero to Hours, Minutes, Seconds

VB .NET:

I have a counter that starts from 00 hours, (as one label),  00 minutes (as one label), and 00 seconds (as one label) except that when the counter starts It takes the 00 and makes them 0 (for numbers 0 - 9).  I need to be able to make the zero stay (while in that 0 - 9 range).  I think I need to pass the integer to a string and pad it with an extra 0 but for the life of me can't remember how to do this.

Any help would be greatly appreciated.
-----------------------------------------------------------------------------
Example Snippet:

Dim Hours, Minutes, Seconds As Integer

Private Sub Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer.Tick

        Seconds = Seconds + 1
        SecondsLabel.Text = Seconds
        MinutesLabel.Text = Minutes
        HoursLabel.Text = Hours
        If SecondsLabel.Text = 60 Then Minutes = Minutes + 1
        If SecondsLabel.Text = 60 Then Seconds = 0
        If MinutesLabel.Text = 60 Then Hours = Hours + 1
        If MinutesLabel.Text = 60 Then Minutes = 0

 End Sub
Peter FrostAsked:
Who is Participating?
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Use Integer.ToString():

        SecondsLabel.Text = Seconds.ToString("00")
        MinutesLabel.Text = Minutes.ToString("00")
        HoursLabel.Text = Hours.ToString("00")
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Though this kind of "timer" is going to get inaccurate over time as the Tick() event does not fire at exactly the Interval you specify...

Instead, consider using the DateTime and TimeSpan Classes like this:

Public Class Form1

    Private startDT As DateTime

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        startDT = DateTime.Now
        Timer1.Interval = 500 ' how often we update the clock...not used to calculate the time!
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim ts As TimeSpan = DateTime.Now.Subtract(startDT)
        Label1.Text = ts.Hours.ToString("00") & ":" & ts.Minutes.ToString("00") & ":" & ts.Seconds.ToString("00")
    End Sub

End Class
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.