ONYX
ONYX

Reputation: 5859

DateTime Difference in time and milliseconds

I need the difference of two datetime down to the millisecond comparison the first datetime is going to be less than the second, its to stop a loop in the gridviews delete event

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    if (!Ok2Delete(e.RowIndex)) return;    

    // your logic goes here and the above IF statement 
    // will hopefully guarantee your code to run once.
}
private bool Ok2Delete(int ri) // ri is the record index to be deleted
{
    if (Session["ri"] == null ||
        (!((ri == ((int)Session["ri"])) &&
        (DateTime.Now.Subtract((DateTime)Session["ri_time_stamp"]).Seconds < 2))))
    {
        Session["ri"] = ri;
        Session["ri_time_stamp"] = DateTime.Now;
        return true;
    }
    return false;
}

this code isn't working as expected

Upvotes: 2

Views: 12553

Answers (3)

competent_tech
competent_tech

Reputation: 44931

You will want something like this (using TotalMilliseconds of the TimeSpan that is the result of subtracting the two datetime objects):

DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now;

Console.WriteLine(dt2.Subtract(dt1).TotalMilliseconds.ToString());

For your specific scenario:

DateTime.Now.Subtract((DateTime)Session["ri_time_stamp"]).TotalMilliseconds < 500

Update

Based on comments and review of the code, the issue is not related to time difference. Instead the problem is in the RowDeleting code. The following line:

if (!Ok2Delete(e.RowIndex)) return;  

should be changed to

if (!Ok2Delete(e.RowIndex)) {
    e.Cancel = true; 
    return;
}  

Upvotes: 2

agent-j
agent-j

Reputation: 27913

Use .TotalSeconds... otherwise a TimeSpan of 122 TotalSeconds will be 2 seconds.

private bool Ok2Delete(int ri) // ri is the record index to be deleted
{
    if (Session["ri"] == null ||
       (!((ri == ((int)Session["ri"])) &&
       (DateTime.Now.Subtract((DateTime)Session["ri_time_stamp"]).TotalSeconds < 2))))
    {
       Session["ri"] = ri;
       Session["ri_time_stamp"] = DateTime.Now;
       return true;
    }
    return false;
}

Upvotes: 2

geofftnz
geofftnz

Reputation: 10092

(end - start).TotalMilliseconds, where start and end are DateTime

Be aware that you may not be able to get millisecond precision out of DateTime.Now(). See this question. You can use a Stopwatch if you need finer precision.

Upvotes: 2

Related Questions