Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulty comparing differences in DateTimes

I have a DateTime variable called "lastActivated", that is set to DateTime.Now when the Form_Activated event fires. The goal is to make sure something doesn't happen within the first 1 second of a user clicking the screen from another screen.

    DateTime? lastActivate = null; //used to determine the last time the screen was focused. 
    private void Form1_Activated(object sender, EventArgs e)
    {
        lastActivate = DateTime.Now;
    }

The code for determining whether it has been longer than 1 second looks like

    TimeSpan oneSec = new TimeSpan(0,0,1);

    if (lastActivate == null || (TimeSpan)(lastActivate - DateTime.Now) > oneSec)
    {
        //stuff
    }

The above if statement always, ALWAYS fails. Even when the values are:

    lastActivate    {11/30/2013 10:23:21 AM}    System.DateTime?
    now {11/30/2013 10:32:48 AM}    System.DateTime

(I made a temp value DateTime now = DateTime.Now so I could paste the value here, since I couldn't directly access DateTime.Now's value)

Does anyone have any suggestions on what I'm doing wrong, and what I should change to get it to accomplish the goal I am after?

Thanks!

like image 344
user1548103 Avatar asked Feb 13 '26 23:02

user1548103


1 Answers

You can test the time between two dates by doing this:

var lastActivated = DateTime.Now;

if (DateTime.Now.Subtract(lastActivated).TotalSeconds > 1)
{
    // Do whatever you need.
}

DateTime.Subtract(DateTime) returns a TimeSpan of the time difference between the two given dates.

like image 159
matth Avatar answered Feb 16 '26 11:02

matth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!