How to display updated time as system time on a label using c#?
I want to display current time on开发者_如何转开发 a label using C# but time will continuously change as system time changes. How can I do this?
Add a new Timer control to your form, called Timer1, set interval to 1000 (ms), then double click on the Timer control to edit the code-behind for Timer1_Tick and add this code:
this.label1.Text = DateTime.Now.ToString();
You can Add a timer control and specify it for 1000 millisecond interval
private void timer1_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt");
}
Add a Timer
control that is set to fire once every second (1000 ms). In that timer's Tick
event, you can update your label with the current time.
You can get the current time using something like DateTime.Now
.
Try the following code:
private void timer1_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString("hh:mm:ss");
}
You must set the timer to be enabled also, either in code, or in the properties window.
in code, please type the following in the form load section:
myTimer.Enabled = true;
myTimer.Interval = 1000;
After that, make sure your timer event is similar to this:
private void myTimer_Tick(object sender, EventArgs e)
{
timeLabel.Text = DateTime.Now.ToString("hh:mm:ss");
}
Since the timer interval is not exact your update could be in bad sync and will be drifting with respect to the actual seconds transition. At some events you will lag behind or before the transition and miss updates in your time display
Instead of polling att high frequency to fire the update at the change of the seconds this method may grant you some respect.
If you like regulators you can adjust your time update to be safely located 100 ms after the actual second transition by adjusting the 1000 ms timer using the Millisecond property of the timestamp you want to display.
In the timer event code do something like this:
//Read time
DateTime time = DateTime.Now;
//Get current ms offset from prefered readout position
int diffms = time.Millisecond-100;
//Set a new timer interval with half the error applied
timer.Interval = 1000 - diffms/2;
//Update your time output here..
Next timer interval should then trigger closer to the selected point 100 ms after the seconds transition. When at the Transition+100ms the error will toggle +/- keeping your readout position in time.
private int hr, min, sec;
public Form2()
{
InitializeComponent();
hr = DateTime.UtcNow.Hour;
min = DateTime.UtcNow.Minute;
sec = DateTime.UtcNow.Second;
}
//Time_tick click
private void timer1_Tick(object sender, EventArgs e)
{
hr = DateTime.UtcNow.Hour;
hr = hr + 5;
min = DateTime.UtcNow.Minute;
sec = DateTime.UtcNow.Second;
if (hr > 12)
hr -= 12;
if (sec % 2 == 0)
{
label1.Text = +hr + ":" + min + ":" + sec;
}
else
{
label1.Text = hr + ":" + min + ":" + sec;
}
}
精彩评论