将SQL Server中的两个日期时间值与c#进行比较

5 c# comparison datetime

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

P D*_*ddy 16

在比较C#中生成的DateTime时要小心.C#中的DateTime结构比SQL Server中的datetime 1类型具有更高的精度.因此,如果您在C#中生成DateTime(比如说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);
Run Code Online (Sandbox Code Playgroud)

}

返回以下示例结果.

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
Run Code Online (Sandbox Code Playgroud)

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

另请参阅:此博客文章

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


Nol*_*rin 7

标准比较运算符(例如,等于,小于,大于)为DateTime类型重载.因此,您可以简单地执行以下测试:

var foo = DateTime.Parse("01/01/1900");
var bar = DateTime.Now;

var test1 = foo == bar; // false
var test2 = foo != bar; // true
var test3 = foo < bar; // true
var test4 = foo > bar; // false
Run Code Online (Sandbox Code Playgroud)


Jos*_*eph 6

您可以使用DateTime.CompareTo方法.

用法是这样的:

firstDateTime.CompareTo(secondDatetime);
Run Code Online (Sandbox Code Playgroud)

并返回一个int作为结果,表明

小于零 - 此实例早于值.

零 - 此实例与值相同.

大于零 - 此实例晚于值.


Chr*_*isF 5

假设您要检查两个DateTime是否相同,就是这样:

TimeSpan span = dateTime2 - dateTime1;
if (span == TimeSpan.Zero)
{
    // The times are the same
}
Run Code Online (Sandbox Code Playgroud)

你需要将其转换System.Data.SqlTypes.SqlDateTimeSystem.DateTime第一个,正如echosca在他的回答中指出的那样.

虽然应该有一些允许的舍入误差(在毫秒范围内),因为这些可能是真实的派生值,因为简单的相等性不够好.你需要这样的东西:

if (Math.Abs(span.TotalMilliseconds) < 10.0)
{
    // The times are within the allowed range
}
Run Code Online (Sandbox Code Playgroud)

如果您只想比较一个日期是在另一个日期之前还是之后,请使用DateTime.CompareTo其他人建议的方法.