How do you compare DateTime objects using a specified tolerance in C#?

前端 未结 7 809
清酒与你
清酒与你 2020-12-29 20:07

By default C# compares DateTime objects to the 100ns tick. However, my database returns DateTime values to the nearest millisecond. What\'s the best way to compare two DateT

相关标签:
7条回答
  • 2020-12-29 20:52

    I’ve created extension methods IsSimilar

    public static bool IsSimilar(this DateTime? lhs, DateTime? rhs, TimeSpan tolerance)
    {
        if (!lhs.HasValue && !lhs.HasValue) return true;//both are null
        if (!lhs.HasValue || !lhs.HasValue) return false;//one of 2 is null
        return IsSimilar(lhs.Value, rhs.Value, tolerance);
    }
    public static bool IsSimilar(this DateTime lhs, DateTime rhs, TimeSpan tolerance)
    {
        return (lhs - rhs).Duration() <= tolerance;
     }
    
    0 讨论(0)
提交回复
热议问题