Reputation: 3
Hi I am implementing the simple Clock.
My requirement is I want my clock to execute with the time I set, not the System Time.
I have implemented using timer but it is not in sync.
private void button1_Click(object sender, EventArgs e)
{
//dtvalue =
dtvalue = DateTime.Parse("11:33:05");
label1.Text = dtvalue.ToString("HH : mm : ss : fff");
timer1.Interval = 100;
timer1.Tick += new EventHandler(timer_Tick);
timer1.Start();
}
void timer_Tick(object sender, EventArgs e)
{
dtvalue = dtvalue.AddMilliseconds(100);
label1.Text = dtvalue.ToString("HH : mm : ss : fff");
}
I want it to get implement exactly as a system clock with the time I give. thanks for your help in advance –
Upvotes: 0
Views: 578
Reputation: 1499800
I would strongly avoid repeatedly adding a particular amount of time - timers aren't going to fire exactly on time, so you'll end up drifting due to that.
Instead, remember the difference between the system clock and add that difference whenever you want:
TimeSpan difference = ...;
void timer_Tick(object sender, EventArgs e)
{
DateTime now = DateTime.Now; // Or UtcNow, see later
DateTime adjusted = now + difference;
label1.Text = adjusted.ToString("HH : mm : ss : fff");
label2.Text = now.ToString("HH : mm : ss : fff");
}
You might want to consider using DateTime.UtcNow
instead of DateTime.Now
, depending on whether you want your custom clock to change value when the time zone offset changes. We don't know what you're really trying to achieve, which makes it hard to pin that down.
Upvotes: 2