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

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

    By default C# compares DateTime objects to the millesecond.

    Actually the resolution is to the 100ns tick.

    If you're comparing two DateTime values from the database, which have 1s resolution, no problem.

    If you're comparing with a DateTime from another source (e.g. the current DateTime using DateTime.Now)), then you need to decide how you want the fractions of a second to be treated. E.g. rounded to nearest or truncated? How to round if it's exactly half a second.

    I suggest you round or truncate to an integral number of seconds, then compare with the value from the database. Here's a post that describes how to round a DateTime (this example rounds to minutes, but the principal is the same).

提交回复
热议问题