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





0/5 (0 vote)
A simple way to determine when to execute something based on the local systems time using .NET DateTime and TimeSpan objects.
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);