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

前端 未结 7 872
清酒与你
清酒与你 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:49

    You need to remove the milliseconds component from the date object. One way is:

        DateTime d = DateTime.Now;
        d.Subtract(new TimeSpan(0, 0, 0, 0, d.Millisecond));
    

    You can also subtract two datetimes

    d.Subtract(DateTime.Now);

    This will return a timespan object which you can use to compare the days, hours, minutes and seconds components to see the difference.

提交回复
热议问题