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

时间:2009-06-20 14:40:57

标签: c# datetime comparison

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

9 个答案:

答案 0 :(得分:15)

在比较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);

}

返回以下示例结果。

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

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

另请参阅:this blog post

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

答案 1 :(得分: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

答案 2 :(得分:6)

您可以使用DateTime.CompareTo方法。

用法是这样的:

firstDateTime.CompareTo(secondDatetime);

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

  

小于零 - 此实例早于值。

     

零 - 此实例与值相同。

     

大于零 - 此实例晚于值。

答案 3 :(得分:5)

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

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

首先,您需要将System.Data.SqlTypes.SqlDateTime转换为System.DateTime,正如echosca在answer中指出的那样。

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

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

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

答案 4 :(得分:1)

您需要将sql中的值放到C#DateTime对象中,然后在C#中进行比较。以下是来自MSDN的link有关如何操作的信息。

答案 5 :(得分:1)

从数据库中检索时,您应该能够使用SqlDataReader转换为正确的.NET类型。 (或使用DataTable / DataSet,它会自动执行此操作)。

SqlDataReader dr = cmd.ExecuteReader();
DateTime dt = dr.GetDateTime(dr.GetOrdinal("someDateTimeColumn"));

那么你可以正常比较:

DateTime otherDate = DateTime.Now;
int compResult = dt.CompareTo(otherDate);

if(compResult > 0) { Console.Write("dt is after otherDate"); }
else if(compResult < 0) { Console.Write("dt is before otherDate"); }
else { Console.Write("dt is equal to otherDate"); }

答案 6 :(得分:1)

System.Data.SqlTypes.SqlDateTime和System.DateTime使用不同的底层结构来表示日期。

SqlDateTime表示1753年1月1日至9999年12月31日的范围,精度为3.33毫秒

DateTime(.NET Framework类型)表示介于0001年1月1日到12月31日9999到100纳秒精度之间的范围

比较日期时应注意这些界限。缓解比较问题的一种策略可能是将所有内容都转换为System.DateTime,然后执行比较。

您可以使用SqlDateTime结构的Value属性(返回System.DateTime)来优雅地进行比较,而无需显式转换。

您可能会发现this article信息丰富。

答案 7 :(得分:0)

DateTime结构覆盖GreterThen,GreaterThenOrEqual,LesserThen,LesserThenOrEqual operater,Equalty operater。

DateTime dateTime1, dateTime2;
dateTime1 = DateTime.Now;
dateTime2 = //set value from database;

// all this operations are legal
if(dateTime1 == dateTime2){}
if(dateTime1 > dateTime2){}
if(dateTime1 < dateTime2){}

答案 8 :(得分:0)

我希望您发现这篇文章(DATEDIFF Function Demystified)很有用,虽然它特定于SQL中的日期时间,但它有助于理解它在数据库端的处理方式。