It's a simple clock
My Timer1_Tick
get that code:
LocalTime.Text = TimeOfDay.ToString("h:mm:ss tt")
How to add 6 hours to it? Thank you
It's a simple clock
My Timer1_Tick
get that code:
LocalTime.Text = TimeOfDay.ToString("h:mm:ss tt")
How to add 6 hours to it? Thank you
You should not use labels and textboxes to store your data (a time in this case). Labels should only be used to display some information and textboxes to display and enter information. Store your data in variables, fields and properties.
Define this field in the form
Dim t As Date = Date.Now
In the method
t = t.AddHours(6)
LocalTime.Text = t.ToString("h:mm:ss tt")
I.e. you always work with the value stored in the field and then update the label text from it.
Since the time in the label is stored as a string, you cannot add hours easily. You would have to convert it back to a Date structure, add the hours and then convert it back to a string.
If you want to display several clocks in the Timer_Tick you can do this (note that Date
in VB is just an alias for the System.DateTime structure):
Dim local = DateTime.Now
LocalTime.Text = local.ToString("h:mm:ss tt")
AnotherLabel.Text = local.AddHours(6).ToString("h:mm:ss tt")
YetAnotherLabel.Text = local.AddHours(-2).ToString("h:mm:ss tt")
DateTime.TimeOfDay
is a TimeSpan. Thus, you could use Hours
property or Add
method to change the value. For example:
LocalTime.Text = TimeOfDay.Add(TimeSpan.FromHours(6)).ToString("hh\:mm\:ss")
To subtract hours use Subtract method instead of Add
. Also, the same result could be obtained by using Add
method with negative TimeSpan values:
LocalTime.Text = TimeOfDay.Add(TimeSpan.FromHours(-6)).ToString("hh\:mm\:ss")
Note, a TimeSpan
represents a time interval. Let, there is value of elapsed time that is equal to 56 hours 36 minutes and 12 seconds. The AM/PM mark isn't actual for this value. Thus, to get AM/PM time format you need to use values of DateTime
structure instead of TimeSpan
:
NEWYORK.Text = DateTime.Now.Add(TimeSpan.FromHours(6)).ToString("hh:mm tt")
See details in the Choosing between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo article.