比较从SQL Server两个日期时间值用C# [英] compare two datetime values from SQL Server with c#

查看:138
本文介绍了比较从SQL Server两个日期时间值用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何比较两个日期时间值一个谁是从SQL数据库retreived,另一个是当前的用C#

i want to know how compare two datetime values one who is retreived from sql database and the other is the current one with c#

推荐答案

比较C#中生成DateTime是否时,请注意。该日期时间结构在C#比的datetime 1 在SQL Server类型。所以,如果你生成C#日期时间(比如从 DateTime.Now ),将其存储在数据库中,并检索它回来了,它很可能是不同的。

Beware when comparing DateTimes generated within C#. The DateTime struct in C# has more precision than the datetime1 type in SQL Server. So if you generate a DateTime in C# (say from DateTime.Now), store it in the database, and retrieve it back, it will most likely be different.

例如,下面的代码:

using(SqlConnection conn = new SqlConnection("Data Source=.;Integrated Security=SSPI"))
using(SqlCommand cmd = new SqlCommand("SELECT @d", conn)){
    DateTime now = DateTime.Now;
    cmd.Parameters.Add(new SqlParameter("@d", now));
    conn.Open();
    DateTime then = (DateTime)cmd.ExecuteScalar();
    Console.WriteLine(now.ToString("yyyy/MM/dd HH:mm:ss.fffffff"));
    Console.WriteLine(then.ToString("yyyy/MM/dd HH:mm:ss.fffffff"));
    Console.WriteLine(then - now);



}

}

返回下面的示例结果


2009.06.20 12:28:23.6115968
2009.06.20 12:28:23.6100000
-00:00:00.0015968

因此,在这种情况下,你会想要检查不同的是在一定小量内:

So in this situation, you would want to check that the difference is within a certain epsilon:

Math.Abs((now - then).TotalMilliseconds) < 3

请注意,这不是,如果你比较从数据库中检索2日期时间的问题,或。从第二或更大粒度的组件构建的日期时间

Note that this is not an issue if you're comparing two datetimes retrieved from the database, or a datetime constructed from components with second or larger granularity.

另请参阅:的这个博客帖子

1 <子>见注意的准确性,它提到了舍入到.000,.003或0.007秒增量

这篇关于比较从SQL Server两个日期时间值用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆