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

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

问题描述

解决方案

我想知道如何比较两个日期时间值,一个是从sql数据库中检索的,另一个是当前的c#

当比较在C#中生成的DateTimes时要小心。 C#中的 DateTime 结构的精度高于 datetime 1 键入SQL Server。因此,如果你在C#中生成一个DateTime(例如从 DateTime.Now ),将它存储在数据库中,然后检索它,它很可能会有所不同。 >

例如,下面的代码:

  using(SqlConnection conn = new SqlConnection (Data Source =; Integrated Security = SSPI))
使用(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

因此,在这种情况下,您需要检查差异是否在一定的ε范围内:

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

请注意,如果您要比较从数据库检索的两个数据时间,



另请参阅:此博文



1 请参阅关于准确性的说明,其中提到舍入到.000,.003或.007秒的增量


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#

解决方案

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.

For instance, the following code:

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

}

returns the following sample result.

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

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.

See also: this blog post

1See note about accuracy, where it mentions "Rounded to increments of .000, .003, or .007 seconds"

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

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