将SQL Server中的两个datetime值与c#

编程入门 行业动态 更新时间:2024-10-28 02:28:05
本文介绍了将SQL Server中的两个datetime值与c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道如何比较两个datetime值,一个从sql数据库中获取的另一个值,另一个是c#中的当前值。

解决方案

比较在C#中生成的DateTimes时,请注意。 C#中的 DateTime 结构的精度比 datetime 1 键入SQL Server。所以如果你在C#中生成一个DateTime(比如说从$ code> DateTime.Now ),将它存储在数据库中,并将其重新取回,这很可能是不同的。 >

例如,以下代码:

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

所以在这种情况下,你会想检查一下这个差异是否在某个epsilon内:

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

请注意,如果要比较从数据库检索的两个数据时间,则不是问题,或由具有第二或更大粒度的组件构建的日期时间。

另请参见:这个博文

1 请参阅有关准确性的注意事项,其中提及舍入为0.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中的两个datetime值与c#

本文发布于:2023-11-07 22:19:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567590.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   SQL   Server   datetime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!