Ciaran Gallagher
Ciaran Gallagher

Reputation: 4020

Code never reaching if(DateTime.Now == myTime) value

I have a simple (stupid) bit of code which I'm using to test our error logging mechanism. It attempts to read from a non-existent file. On exception, I set a DateTime value, then I have a while loop. Once the current DateTime is equal to the DateTime value I set, then I pass the exception to my error logging project.

This code starts on a button press. The purpose of this is that I can test what happens when multiple exceptions are thrown from separate user sessions in my ASP.NET application.

So I'd open a few browser sessions, press the 'Exception' button then this code will run. Once the current time matches up with the time I set, then it should throw an exception, but the if(DateTime.Now == run) never evaluates to true. Why?

protected void Button1_Click(object sender, EventArgs e)
{
    try
    {
        string text = System.IO.File.ReadAllText(@"C:\test.txt");
    }
    catch (FileNotFoundException ex)
    { 
        DateTime run = new DateTime(2013, 12, 18, 14, 0, 0);
        bool hasRun = false;

        while (hasRun == false)
        {
            if (DateTime.Now == run)
            {
                ErrorLogger errorLogger = new ErrorLogger(ex);
                hasRun = true;
            }
        }
    }
}

Upvotes: 0

Views: 218

Answers (4)

Alex
Alex

Reputation: 23300

Using a Timer leads to clearer and less risky code (no loops which might go infinite):

catch(FileNotFoundException ex)
{
    // The hard-coded date should of course be a *future* one for the code to have sense
    var interval = new DateTime(2013, 12, 20, 09, 00, 00) - DateTime.Now;

    Timer t = new Timer(interval.TotalMilliseconds);
    t.Elapsed += (s, e) =>
    {
        ErrorLogger errorLogger = new ErrorLogger(ex);
        t.Stop(); // Let it only run once
    };
    t.Start();
}

Upvotes: 1

Mahmoud Fayez
Mahmoud Fayez

Reputation: 3459

Try this out for the if condition:

if (Datetime.Now.Subtract(run).Days == 0)
{
    // code goes here if the run and Datetime.Now are on the same day
}

Upvotes: 0

garf1eld
garf1eld

Reputation: 104

I think you just does not take into account the fact time will never be rounded to seconds. there is always miliseconds. If you want to compare, just use this snippet

var date = DateTime.Now;
date = new DateTime(date.Year,date.Month,date.Day,date.Hour,date.Minute,date.Second)
if (date == run)
{ 

Upvotes: 1

hoekki
hoekki

Reputation: 238

if(DateTime.Now >= run)

similar trap as in checking for equality with float or double

Upvotes: 1

Related Questions