我想知道如何比较两个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.0015968So in this situation, you would want to check that the difference is within a certain epsilon:
Math.Abs((now - then).TotalMilliseconds) < 3Note 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#
发布评论