我有一个Windows窗体,我使用DateTime Class下面的代码,但我想在窗体上使用timing should变量
LblLocalTime.Text = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
LblUTCTime.Text = DateTime.UtcNow.ToString("MM/dd/yyyy HH:mm:ss");
我该怎么办?
答案 0 :(得分:8)
使用Timer类,设置所需的时间间隔
private void Form1_Load()
{
Timer tmr = new Timer();
tmr.Interval = 1000;//ticks every 1 second
tmr.Tick+=new EventHandler(tmr_Tick);
tmr.Start();
}
//change the label text inside the tick event
private void tmr_Tick(object sender, EventArgs e)
{
LblLocalTime.Text = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
LblUTCTime.Text = DateTime.UtcNow.ToString("MM/dd/yyyy HH:mm:ss");
}
答案 1 :(得分:1)
您正在做的只是设置文本一次。您必须不断更新标签以反映当前的DateTime。每隔一秒设置一个计时器并更新每个Tick事件上的标签。
System.Timers.Timer timer = new System.Timers.Timer();
Timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
Timer.Interval = 1000;
private void Timer_Elapsed(object sender, EventArgs e)
{
LblLocalTime.Text = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
LblUTCTime.Text = DateTime.UtcNow.ToString("MM/dd/yyyy HH:mm:ss");
}