[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1788
  • Last Modified:

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


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 Frost
Peter Frost
  • 2
1 Solution
Mike TomlinsonMiddle School Assistant TeacherCommented:
Use Integer.ToString():

        SecondsLabel.Text = Seconds.ToString("00")
        MinutesLabel.Text = Minutes.ToString("00")
        HoursLabel.Text = Hours.ToString("00")
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!
    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

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now