Timer minutes is always 30 seconds out - vb.net

Goodday, I use the below code to start a timer .
Label2.Text = Difference1.TotalMinutes.ToString("N0")
But the minutes are always 30 seconds out. The label shows the time as 1 minute when only 30 seconds have elapsed and thereafter I'm always 30 seconds out.
How can I calibrate this?
Thanks
Rob

If you look at the definition for the TimeSpan.TotalMinutes property it states that it:
Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
Therefore when you use the ToString("N0") format you are telling it that you want no decimal places and since it is a numeric format it will round your value up. You should look at using the TimeSpan Custom Formats in particular in this case the %m Custom Format string. It should look something like this:
Label2.Text = Difference1.TotalMinutes.ToString("%m")
Code I used to test. Timer interval is set to 1000 and is enabled.
Public Class Form1
Dim startTime As DateTime = DateTime.Now
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
Label1.Text = (DateTime.Now - startTime).ToString("%m")
Label2.Text = (DateTime.Now - startTime).TotalSeconds.ToString("N0")
End Sub
End Class

Related

Calculate the amount to pay based on time difference in 2 textboxes VB.Net

enter image description here
I want to get the amount to pay based on time difference of the time in and time out.
example. Time In is : 7:00:00
Time Out is : 13:00:00
The difference is 6 hrs
and lets say that the per hour rate is 10.00, so the amount should be 60.00
thanks! im using vb.net
what im trying to do is like this.
Private Const Format As String = "HH:mm:ss"
'this is the code i used to get the time in
Private Sub btnTimeIn_Click(sender As Object, e As EventArgs) Handles btnTimeIn.Click
TextboxTimeIn.Text = DateTime.Now.ToString(Format)
End Sub
'this is the time out
Private Sub btnTimeOut_Click(sender As Object, e As EventArgs) Handles btnTimeOut.Click
TextboxTimeOut.Text = DateTime.Now.ToString(Format)
'this is what is use to get the time difference
txtAmount.Text = Convert.ToDateTime(TextboxTimeOut.Text).Subtract(Convert.ToDateTime(TextboxTimeIn.Text)).ToString()
End Sub
but instead of showing the time difference, i want to show the amount in the txtAmount. example
if timeDifference <= 60mins , then
txtAmount = 10
else timeDifference > 60mins , then
txtAmount = 20
You want to know 3 things:
How much time passed between checkin and checkout
How many hours is that
Hom much will this cost
These points could be calculated in only one line, but for the sake of clarity we'll clear them one by one:
'let's use some more variables to make this easier
Private Const Format As String = "HH:mm:ss"
Private checkin As DateTime
Private checkout As DateTime
Private rate As Integer = 10
'now with variables!
Private Sub btnTimeIn_Click(sender As Object, e As EventArgs) Handles btnTimeIn.Click
checkin = Now
TextboxTimeIn.Text = checkin.ToString(Format)
End Sub
Private Sub btnTimeOut_Click(sender As Object, e As EventArgs) Handles btnTimeOut.Click
checkout = Now
TextboxTimeOut.Text = checkout.ToString(Format)
'First we check for an amount of hours, then we add one if they overstayed
Dim timeStayed As Integer = checkout.Hour - checkin.Hour
If TimeStayed.Minute > 0 Then timeStayed += 1
'Notice the use of a variable so you can tweak your rates easily
txtAmount.Text = (timeStayed * rate).ToString
End Sub
What you need to remember here is:
Make things easier on you. Don't convert everything all the time.
Follow your own pseudocode. You already knew what to do. Do it.
I used Integers for money... this is bad! You should change this as soon as possible, so your numbers can have decimals! (also you should format the txtAmount as money)
Have fun!

display a message to a label in vb.net at specified times during the day

I would like to display a sentence in a text box at a 5 specific times during the day automatically. for example:
at 5:30 AM,
Textbox1.text = "breakfast"
at 7:30 AM
textbox1.text = "leave for school",
etc.
a timer can just start when the application is launched, although it needs to refer to the local time or some constant time as the program needs to output at the same time each day of the week without me having to change it manually.
The proper way to do it is something like this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Set the interval at startup.
Timer1.Interval = CInt(GetNextNotificationTime().Subtract(Date.Now).TotalMilliseconds)
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'Set the interval at each notification.
Timer1.Interval = CInt(GetNextNotificationTime().Subtract(Date.Now).TotalMilliseconds)
'Not sure whether this is required when the Interval changes or not.
Timer1.Stop()
Timer1.Start()
'Do the work here.
End Sub
Private Function GetNextNotificationTime() As Date
'...
End Function
How you implement that GetNextNotificationTime method depends on how the notification times are stored. The Timer will then Tick only when a notification is due.
You can still do this with a Timer and you wouldn't have to do any math...
Every time the Timer raises a Tick event, you check the value of: System.DateTime.Today.Now.ToString("HH:mm"). If it is equal to your preset time, change the text in the TextBox

Show only relevant numbers from stopwatch

While attempting to make a stopwatch, I noticed that it would display all groups of numbers related to the timer (in this case "00:00:00:00")
In order to show only relevant numbers, and not show the minutes column when a minute hadn't passed, I came up with this code:
Public Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim sw As New Stopwatch
Dim elapsed As TimeSpan = Me.stopwatch.Elapsed
Label1.Text = String.Format("{0:00}:{1:00}",
Math.Floor(elapsed.Seconds),
elapsed.Milliseconds)
If Label1.Text = "60:999" Then
Label1.Text = String.Format("{0:00}:{1:00}:{2:00}",
Math.Floor(elapsed.Minutes),
elapsed.TotalSeconds, elapsed.TotalMilliseconds)
End If
End Sub
When this code is active, the timer will only show the seconds and milliseconds column until it hits a full minute, in which case it will just loop back to 0 seconds and repeat. I'm assuming that the timer just can't detect exactly when label1's text is exactly 60.999, but I'm not sure. What is my logic missing?
Timers are not guaranteed to fire exactly at their interval. I'm assuming your timer is set to go off every 1ms, however when you run your program you'll find it will probably by raised every 3-16ms with a lot of jitter, this is also not helped by the fact the WinForms Timer (which I assume you're using) goes through the Win32 window message pump, rather than its own dedicated (and real-time) thread.
Anyway, the fix is to not compare strings, instead compare the actual time values:
If elapsed.TotalSeconds < 60 Then
label1.Text = String.Format("{0:00}:{1:00}", Math.Floor(elapsed.Seconds), elapsed.Miliseconds)
Else
label1.Text = String.Format("{0:00}:{1:00}:{2:00}", Math.Floor(elapsed.TotalMinutes), Math.Floor(elapsed.Seconds), elapsed.Miliseconds)
End If
Note you shouldn't be displaying TotalSeconds if you're already displaying Minutes.
There's a few problems with your code:
You are declaring a new Stopwatch inside of the Tick event. This is unnecessary.
You're using string comparisons to do something that should be done with math. Your hunch is correct that the exact moment when the label's text is "60:999" is being missed by the timer.
Instead of comparing the label's text value, just look at how many milliseconds (or seconds) have elapsed!
Public Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim elapsed As TimeSpan = Me.stopwatch.Elapsed
If elapsed.TotalSeconds >= 60 Then
Label1.Text = String.Format("{0:00}:{1:00}:{2:00}",
Math.Floor(elapsed.Minutes),
Math.Floor(elapsed.Seconds),
elapsed.Milliseconds)
Else
Label1.Text = String.Format("{0:00}:{1:00}",
Math.Floor(elapsed.Seconds),
elapsed.Milliseconds)
End If
End Sub

Making a clock which would start running from specific time

I'm trying to make a clock which would start running from a specific time - e.g. the user sets the time to be 17.35 and it runs from there. What would be the easiest way to do it? I tried setting the time with Timeserial but couldn't figure out how to add time to it so it didn't get me anywhere.
Ideas?
edit: The idea behind the program is to show the user a normal digital clock that has been sped up.
Add a Label and a Timer component in your form and set the starting date and time (the date won't be visible). So if you set 17:35:00 the time will start from that moment and be updated every second like a clock.
Public Class Form1
Dim startTime As DateTime
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
startTime = New DateTime(2014, 1, 1, 17, 35, 0) 'setting time at 17:35:00
Label1.Text = startTime.ToString("HH:mm:ss")
Timer1.Interval = 1000 '1 tick every second
Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
startTime = startTime.AddSeconds(1)
Label1.Text = startTime.ToString("HH:mm:ss")
End Sub
End Class
Create a form with a timer on it. Set the timer to 1000ms and enable it.
Dim three variables hours, mins, secs. On the timer event, increment the secs. When secs = 60, set secs = 0 and increment the mins; ditto mins to hours, then display the hrs:mins:secs in a format of your choice. Add a button which allows the user to enter starting values for hrs, mins, secs.
Depending on what you mean by 'sped up' you could reduce the delay on the timer if you want it to run faster, as opposed to ahead of local time.

Create a simple timer to count seconds, minutes and hours

I'm trying to create a pretty simple program that basically is a timer.
I have three sets of labels, lbl_seconds, lbl_minutes and lbl_hours.
These labels have the default value of 00:00 and I want the timer to change that for each label. I have googled this but I cannot seem to find any good info on it.
Do I need three separate timers? I have also noticed that the timers have their own tick event handler. I guess it's in this that I need to change the value of the label. How to do just that?
Here is an example of this
Dim timercount As Integer = 60 'The number of seconds
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Timer1.Interval = 1000 'The number of miliseconds in a second
Timer1.Enabled = True 'Start the timer
End Sub
Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
Timer1.Enabled = False 'Stop the timer
timercount = 60 'Reset to 60 seconds
lblOutput.Text = timercount.ToString() 'Reset the output display to 60
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
lblOutput.Text = timercount.ToString() 'show the countdown in the label
If timercount = 0 Then 'Check to see if it has reached 0, if yes then stop timer and display done
Timer1.Enabled = False
lblOutput.Text = "Done"
Else 'If timercount is higher then 0 then subtract one from it
timercount -= 1
End If
End Sub
I think you need something of this sort
Public Function GetTime(Time as Integer) As String
Dim Hrs As Integer 'number of hours '
Dim Min As Integer 'number of Minutes '
Dim Sec As Integer 'number of Sec '
'Seconds'
Sec = Time Mod 60
'Minutes'
Min = ((Time - Sec) / 60) Mod 60
'Hours'
Hrs = ((Time - (Sec + (Min * 60))) / 3600) Mod 60
Return Format(Hrs, "00") & ":" & Format(Min, "00") & ":" & Format(Sec, "00")
End Function
You pass the time (in seconds) you'd like to display on the label's text and the time will be formatted as you like it.
e.g.
lblTime.Text = GetTime(90)
This will display 00:01:30 on the label.
For reference, you can see this project I submitted on FreeVBCode some time ago. The only caveat is the project is in VB6. You should be able to open it in Visual Studio though.
Start off by adding a timer. Call it whatever you like, in this example I will be keeping it as Timer1. Add a label and set the text as: 00:00.
In the code after the class has been set (usually it is Public Class Form1) make a variable as a stopwatch: Dim stopwatch As New Stopwatch
In the timer tick event code, put the following: (Please note that my 00:00 label is called Label1)
Label1.Text = String.Format("{0}:{1}:{2}", watch.Elapsed.Hours.ToString("00"), watch.Elapsed.Minutes.ToString("00"), watch.Elapsed.Seconds.ToString("00"))
Use one timer and in event sub change value of your labels.
You need one timer and three counter for seconds, minutes and hours.
Count minutes, then modulo minutes / 60, if return 0 then start count minutes.
Modulo minutes/60, if return 0 then start count hours.