Reputation: 13
Hello I do this code for does this statement ( MessageBox.Show("done ");
) when the time is between 11:47 , 11:49
public Form1()
{
InitializeComponent();
System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
MyTimer.Interval = (1 * 60 *500 ); // 1 mins
MyTimer.Tick += new EventHandler(times);
MyTimer.Start();
}
private void times(object sender, EventArgs e)
{
DateTime t1 = DateTime.Parse("11:47:00.000");
DateTime t2 = DateTime.Parse("11:49:00.000");
TimeSpan now = DateTime.UtcNow.TimeOfDay;
if (t1.TimeOfDay <= now && t2.TimeOfDay >= now)
{
MessageBox.Show("done ");
}
but it doesn't working
Upvotes: 0
Views: 1097
Reputation: 39122
Here's how to make it trigger at 11:48...
private System.Windows.Forms.Timer MyTimer;
private TimeSpan TargetTime = new TimeSpan(11, 48, 0);
public Form1()
{
InitializeComponent();
MyTimer = new System.Windows.Forms.Timer();
MyTimer.Interval = (int)MillisecondsToTargetTime(TargetTime);
MyTimer.Tick += new EventHandler(times);
MyTimer.Start();
}
private double MillisecondsToTargetTime(TimeSpan ts)
{
DateTime dt = DateTime.Today.Add(ts);
if (DateTime.Now > dt)
{
dt = dt.AddDays(1);
}
return dt.Subtract(DateTime.Now).TotalMilliseconds;
}
private void times(object sender, EventArgs e)
{
MyTimer.Stop();
MessageBox.Show("It's " + TargetTime.ToString(@"hh\:mm"));
MyTimer.Interval = (int)MillisecondsToTargetTime(TargetTime);
MyTimer.Start();
}
Upvotes: 0
Reputation: 1967
You created DateTime and Timespan, where DateTime is a point in time and TimeSpan is an interval between two points in time.
Also a second has 1000 milliseconds, so better use:
MyTimer.Interval = (1 * 60 * 1000); // 1 mins
Try this:
public Form1()
{
InitializeComponent();
System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
MyTimer.Interval = (1 * 60 * 1000); // 1 mins
MyTimer.Tick += new EventHandler(times);
MyTimer.Start();
}
private void times(object sender, EventArgs e)
{
DateTime t1 = DateTime.Parse("11:47:00.000");
DateTime t2 = DateTime.Parse("11:50:00.000");
DateTime now = DateTime.Now;
if (t1 <= now && t2 >= now)
{
MessageBox.Show("done ");
}
}
Upvotes: 1