compare two datetime values from SQL Server with c#

后端 未结 9 2261
终归单人心
终归单人心 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:38

    Assuming that you want to check that the two DateTimes are equivalent there's this way:

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

    You will need to convert the System.Data.SqlTypes.SqlDateTime to System.DateTime first of course, as echosca points out in his answer.

    Though there should some allowed rounding error (in the millisecond range say), as these are likely to be real-world derived values, as the simple equality wouldn't be good enough. You'd need something like this:

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

    If you just want to compare whether one date is before or after another use the DateTime.CompareTo method as others have suggested.

提交回复
热议问题