We help IT Professionals succeed at work.

How to compare DateTime.Now.TimeOfDay to TImespan

R1ND3R
R1ND3R asked
on
Medium Priority
2,729 Views
Last Modified: 2012-06-27
I have a web service that need to run at a specific time each day. Within one of my events, I have the following if condition:

if (DateTime.Now.TimeOfDay.Equals(new TimeSpan(16, 00, 00)))
{
    //Do Something
}

Open in new window


As you can see, I want my code within my IF condition to fire at 16:00. For some reason, the condition is never true.

I have manually output DateTime.Now.TimeOfDay.Hours and DateTime.Now.TimeOfDay.Minutes to ensure I getting the correct minutes and hours.

Am I missing something?
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
The only time that snippet of code would return true is if it were executed at exactly 4 PM. Even one second off, and the condition is not met. I believe in this case you would want to inspect the values of both the hours and minutes properties.
Lara FEA
CERTIFIED EXPERT

Commented:
CERTIFIED EXPERT
Most Valuable Expert 2015
Distinguished Expert 2018

Commented:
You need some basic functionality like this:

bool trigToday = false;

TimeSpan trig = TimeSpan.FromHours(16);
TimeSpan now = DateTime.Now.TimeOfDay;
if (TimeSpan.Compare(now, trig) <= 0)
{
    trigToday = false;
}
else
{
    if (trigToday == false)
    {
        // Run code.
        Console.WriteLine("Trigged");
        trigToday = true;
    }
}

Open in new window


where you create a method to call to check if it's on or after the time to run your code, and a property (from trigToday) to tell if the code has run for today.

Then you can call the method at the interval or whenever you prefer or are able to.

/gustav

Author

Commented:
Thanks for all the replies. I still cannot get my web service to fire at an exact time. Here is my code:

Timer timer = new Timer();

        public MembershipExpiryService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            //add line to the file
            AddToFile("Service Started " + DateTime.Now.ToShortTimeString());

            //ad 1: handle Elapsed event
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 1000;

            //ad 3: enabling the timer
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            AddToFile("Service stopped " + DateTime.Now.ToShortTimeString());
            timer.Enabled = false;
        }

        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            AddToFile("Time elapsed event " + DateTime.Now.TimeOfDay.Hours + ":" + DateTime.Now.TimeOfDay.Minutes);
            
            if (DateTime.Now == DateTime.Today.AddHours(8).AddMinutes(30).AddSeconds(00))
            {
                AddToFile("Time equals " + DateTime.Now.ToShortTimeString());

            }
        }

Open in new window


Basically, everytime the OnElapsedTime is fired I am checking the time. If the time is correct, then I will carry out some process (at the moment just writing to a text file).

cactus_data, I have tried your code but it will fire every time throughout the hour.
CERTIFIED EXPERT
Most Valuable Expert 2015
Distinguished Expert 2018
Commented:
> .. I have tried your code but it will fire every time throughout the hour.

It was not finished code, just to demonstrate the functionality.

If it fires more that once per day (don't know the exact meaning of "throughout the hour", sorry), that's probably because the line

bool trigToday = false;

is called within the loop. It must be placed outside as a property or a static where the value of true will be kept when it has been trigged after 16.00.

/gustav
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
I was thinking something along the lines of:

if (DateTime.Now.Hour == 16 && DateTime.Now.Minute == 0)

Open in new window