Click here to Skip to main content
15,923,789 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
Hey guys,

I'm having trouble about my program comparing the system time and the one I input through a Set button.

My program has 4 variables which are:
startHr - Hour
startMin - Minute
endHr - Hour
endMin - Minute


my goal is that, when the system time's hour and minute falls in startHr and startMin it does something and when it reaches endHr and endMin it stops. And when system time's hour and minute doesn't fall on what I've input, it does nothing. I'm having trouble on how to code :( please help. I'm still a newbie.
Posted
Updated 13-Mar-14 7:23am
v2
Comments
Krunal Rohit 13-Mar-14 10:17am    
You can use DateTime.Now property of DateTime object, which will give you the current Date and Time.
Now get the Minutes, hours in the variables using mentioned property, and do the operations.

-KR
BillWoodruff 13-Mar-14 10:43am    
Please don't repost the same question you posted only 21 hours ago.
Matt T Heffron 13-Mar-14 13:23pm    
And was answered!

1 solution

Hi,

You can use Timer class. It has Tick event which is triggered with Interval you set.

C#
private Timer _timer;
private int _startHour;
private int _startMin;
private int _endHour;
private int _endMin;

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    _timer = new Timer();
    _timer.Interval = 1000; // 1000ms = 1 sec.
    _timer.Tick += new EventHandler(_timer_Tick);
}

private void _timer_Tick(object sender, EventArgs e)
{
    var currentTime = DateTime.Now;
    if (currentTime.Hour == _startHour && currentTime.Minute == _startMin)
    {
        // Start your task
    }
    else if (currentTime.Hour == _endHour && currentTime.Minute == _endMin)
    {
        // Stop your task
    }
}

private void button1_Click(object sender, EventArgs e)
{
    // Set your time to variables
    //_startHour =
    //_startMin =
    //_endHour =
    //_endMin =
    _timer.Enabled = true;
}


Depending on task which you want to execute you should consider runing it in thread.

I hope i helped you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900