Click here to Skip to main content
15,880,796 members
Articles / Programming Languages / C#
Tip/Trick

Using DateTime and TimeSpan objects to test for a specific time interval.

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
16 Feb 2011CPOL 8.7K   2  
A simple way to determine when to execute something based on the local systems time using .NET DateTime and TimeSpan objects.
C#
bool work = true;
//execute at 2:06 PM
TimeSpan timeToExecute = new TimeSpan(14,6,00);
do
{
  DateTime nowTime = DateTime.Now;
  TimeSpan systemTime = new TimeSpan(nowTime.TimeOfDay.Hours,
                                       nowTime.TimeOfDay.Minutes,
                                       nowTime.TimeOfDay.Seconds);
  Console.WriteLine(systemTime);
  Console.WriteLine(timeToStop);
 
  if(timeToExecute.CompareTo(systemTime) == 0)
  {
    //Execute whatever you need to here.
    Console.WriteLine("END");
  }
}while(work);

License

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


Written By
Systems Engineer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --