compare two datetime values from SQL Server with c#

后端 未结 9 2130
终归单人心
终归单人心 2021-01-05 20:48

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#

相关标签:
9条回答
  • 2021-01-05 21:19

    System.Data.SqlTypes.SqlDateTime and System.DateTime use different underlying structures to represent dates.

    SqlDateTime represents the range January 1, 1753 to December 31, 9999 to an accuracy of 3.33 milliseconds

    DateTime(.NET Framework type) represents the range between Jan 1, 0001 to Dec,31 9999 to the accuracy of 100 nanoseconds

    You should be careful of these boundaries when comparing dates. One tactic to alleviate problems in comparisons could be to cast everything to System.DateTime and then perform the compare.

    You can use the Value property of the SqlDateTime struct (which returns a System.DateTime) to do the comparison elegantly and without explicit casting.

    You might find this article informative.

    0 讨论(0)
  • 2021-01-05 21:23

    When retrieved from the database, you should be able to use a SqlDataReader to cast to the correct .NET type. (or use DataTable/DataSet, which automatically does this).

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

    then you can compare normally:

    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"); }
    
    0 讨论(0)
  • 2021-01-05 21:32

    I hope you find this article (DATEDIFF Function Demystified) useful, although it's specific to datetime in SQL, it's helpful for understanding how it's handled on the database side.

    0 讨论(0)
  • 2021-01-05 21:35

    The standard comparison operators (e.g. equality, less than, greater than) are overloaded for the DateTime type. So you can simply perform tests such as the following:

    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
    
    0 讨论(0)
  • 2021-01-05 21:35

    You can use the DateTime.CompareTo method.

    Usage is like this:

    firstDateTime.CompareTo(secondDatetime);
    

    and returns an int as a result which indicates

    Less than zero - This instance is earlier than value.

    Zero - This instance is the same as value.

    Greater than zero - This instance is later than value.

    0 讨论(0)
  • 2021-01-05 21:35

    You need put the value from sql to C# DateTime object, and then compare them in C#. Here is a link from MSDN on how to do it.

    0 讨论(0)
提交回复
热议问题