tags:

views:

1408

answers:

4

Hi, I'm trying to make a countdown timer in my app. I already know the countdown time which is 4 minutes. I have a timer which ticks avery seconds. Now from that how can I update my textbox so that it shows the time remaining in the foirmat HHMMSS?

EDIT: the problem I'm having is calculating the remaining time. What should I use? timestamp?

A: 

Add an event handler for the timer and have it calculate the remaining time, format a string and update the textbox.

To track time and calculate the difference you can use Environment.TickCount - it's the simplest variant. Save the timestamp at the moment you start the countdown and get it each time the event handler is called.

sharptooth
+1  A: 

The best way to keep track of the time is to log the start by using DateTime.Now. Then you can see the difference at any time by subtracting the saved value.

Dim diff = DateTime.Now - savedTime
Dim remaining = TimeSpan.FromMinutes(4) - diff

To get the format you want, just pass it to the .ToString function as a string

Dim readable = remaining.ToString("hh:mm:ss")
JaredPar
+3  A: 

Before you start counting down, note the current time using something like

Dim endTime as DateTime = DateTime.Now.Add(TimeSpan.FromMinutes(4))

Then when your tick events occur, you can figure out how much time is left using

Dim timeLeft as TimeSpan = endTime.Subtract(DateTime.Now)

You can format timeLeft as needed, possibly using .ToString("hh:mm:ss") mentioned by Jared

You can read the docs on TimeSpans and DateTimes for more info on how to use them.

Daniel LeCheminant
A: 
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Timer1.Interval = 500
    Timer1.Start()
End Sub
Dim stpw As New Stopwatch
Dim CountDownFrom As Integer = 4 * 60 'as seconds
Dim CountDown As New TimeSpan
Private Sub StartCountDown()
    CountDown = TimeSpan.FromSeconds(CountDownFrom)
    stpw.Stop() : stpw.Reset() : stpw.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    If Not stpw.IsRunning Then Exit Sub
    Dim TimeRemaining As TimeSpan = CountDown - stpw.Elapsed
    Label1.Text = TimeRemaining.Hours.ToString.PadLeft(2, "0"c) & ":" & _
                    TimeRemaining.Minutes.ToString.PadLeft(2, "0"c) & ":" & _
                    TimeRemaining.Seconds.ToString.PadLeft(2, "0"c)
    If TimeRemaining.TotalMilliseconds <= 0 Then stpw.Stop()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    StartCountDown()
End Sub
dbasnett