DateTime时间和毫秒的差异

时间:2012-01-10 03:56:25

标签: c# asp.net c#-4.0

我需要将两个日期时间的差异缩小到毫秒比较,第一个日期时间将小于第二个,它将在gridviews删除事件中停止循环

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;
}

此代码未按预期工作

3 个答案:

答案 0 :(得分:2)

使用.TotalSeconds ...否则TimeSpan为122 TotalSeconds将为2秒。

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;
}

答案 1 :(得分:1)

你会想要这样的东西(使用TimeSpan的TotalMilliseconds,它是减去两个datetime对象的结果):

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

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

针对您的具体情况:

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

<强>更新

根据对代码的评论和审核,该问题与时差无关。相反,问题出在RowDeleting代码中。以下一行:

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

应改为

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

答案 2 :(得分:1)

(end - start).TotalMilliseconds,其中开头和结尾为DateTime

请注意,您可能无法从DateTime.Now()中获得毫秒精度。见this question。如果您需要更精确的话,可以使用Stopwatch