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 every seconds. Now from that how can I update my TextBox
so that it shows the time remaining in the format HHMMSS
?
EDIT: the problem I'm having is calculating the remaining time. What should I use? Timestamp?
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 TimeSpan s and DateTime s for more info on how to use them.
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")
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.