c# - 与 MaxValue 的日期比较不起作用

标签 c# datetime

我有一个名为 BoughtDate 的可为 null 的 Date 属性。 我正在尝试以下操作:

if( item.BoughtDate.Value.Equals( DateTime.MaxValue) ) item.BoughtDate= null;

也试过这个:

if( item.BoughtDate.Equals( DateTime.MaxValue) ) item.BoughtDate=null;

调试时,我的 BoughtDateDateTime.MaxValue 看起来完全一样 - 但它说它不一样(不设置我的 item.BoughtDate 为空)

为什么我的比较不起作用?

最佳答案

正如@PaulSuart 在评论中指出的那样,问题可能在于毫秒精度。 DateTime.MaxValue.TimeOfDay{23:59:59.9999999},但是你的 BoughtDate.TimeOfDay 可能是 {23:59: 59.9990000},所以他们不相等。

我会做的只是比较日期,我认为在大多数情况下这就足够了:

if( item.BoughtDate.Value.Date.Equals( DateTime.MaxValue.Date) ) item.BoughtDate= null;

关于c# - 与 MaxValue 的日期比较不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44324689/

相关文章:

python - Pandas 中的字符串到日期时间格式

c# - MongoDB Driver Query * Filter Definition Builder * Nin $nin 不在过滤器中

c# - 如何在 C# 中使用 system.drawing 将居中文本绘制到 jpg 上

c# - 使用 [X] 按钮打开/显示其他表单单击 C#

datetime - 如果未指定,XML 架构 dateTime 的默认时区是什么?

Java 字符串到日期时间

python - 有没有办法在 Python 中推断日期是否是 DST(夏令时)更改发生的实际日期?

c# - 如何在多线程中获取线程状态

java - C#扫描局域网自动发现Web Service的方法

sql比较今天的日期时间