DateTime Comparison Precision

后端 未结 10 631
攒了一身酷
攒了一身酷 2020-12-29 04:24

I\'m doing DateTime comparison but I don\'t want to do comparison at second, millisecond and ticks level. What\'s the most elegant way?

If I simply compare the DateT

10条回答
  •  佛祖请我去吃肉
    2020-12-29 04:41

    I've written this to help myself:

        internal class ImpreciseCompareDate : IComparer
    {
        private readonly double _Tolerance;
    
        public ImpreciseCompareDate(double MillisecondsTolerance)
        {
            _Tolerance = MillisecondsTolerance;
        }
    
        public int Compare(DateTime x, DateTime y)
        {
            return Math.Abs((x - y).TotalMilliseconds) < _Tolerance ? 0 : x.CompareTo(y);
        }
    }
    

    Tolerance can be set to (10d/3d) to account for SQL servers 1/300th of a ms. If tolerance is exceeded, delegate to default comparer.

提交回复
热议问题