比较可空的日期时间对象

我有两个可以为空的日期时间对象,我想比较两者。 最好的方法是什么?

我已经尝试过了:

DateTime.Compare(birthDate, hireDate); 

这是一个错误,也许是期望System.DateTime类型的日期,我有Nullable日期时间。

我也尝试过:

 birthDate > hiredate... 

但结果不如预期……任何建议?

要比较两个Nullable对象,请使用Nullable.Compare如:

 bool result = Nullable.Compare(birthDate, hireDate) > 0; 

你也可以这样做:

使用Nullable DateTime的Value属性。 (记住要检查两个对象是否都有一些值)

 if ((birthDate.HasValue && hireDate.HasValue) && DateTime.Compare(birthDate.Value, hireDate.Value) > 0) { } 

如果两个值都相同DateTime.Compare将返回0

就像是

 DateTime? birthDate = new DateTime(2000, 1, 1); DateTime? hireDate = new DateTime(2013, 1, 1); if ((birthDate.HasValue && hireDate.HasValue) && DateTime.Compare(birthDate.Value, hireDate.Value) > 0) { } 

Nullable.Equals指示两个指定的Nullable(Of T)对象是否相等。

尝试:

 if(birthDate.Equals(hireDate)) 

最好的方法是: Nullable.Compare方法

 Nullable.Compare(birthDate, hireDate)); 

如果您希望将null值视为default(DateTime)您可以执行以下操作:

 public class NullableDateTimeComparer : IComparer { public int Compare(DateTime? x, DateTime? y) { return x.GetValueOrDefault().CompareTo(y.GetValueOrDefault()); } } 

并像这样使用它

 var myComparer = new NullableDateTimeComparer(); myComparer.Compare(left, right); 

另一种方法是为Nullable类型创建一个可比较值的扩展方法

 public static class NullableComparableExtensions { public static int CompareTo(this T? left, T? right) where T : struct, IComparable { return left.GetValueOrDefault().CompareTo(right.GetValueOrDefault()); } } 

你在哪里使用它

 DateTime? left = null, right = DateTime.Now; left.CompareTo(right); 

使用Nullable.Compare方法。 像这样:

 var equal = Nullable.Compare(birthDate, hireDate); 
 Try birthDate.Equals(hireDate) and do your stuff after comparision. or use object.equals(birthDate,hireDate) 

正如@Vishal所说,只需使用Nullable覆盖Equals方法。 它以这种方式实现:

 public override bool Equals(object other) { if (!this.HasValue) return (other == null); if (other == null) return false; return this.value.Equals(other); } 

如果两个可空结构都没有值,或者它们的值相等,则返回true 。 所以,简单地使用

 birthDate.Equals(hireDate) 

我想你可以用以下方式使用这个条件

 birthdate.GetValueOrDefault(DateTime.MinValue) > hireddate.GetValueOrDefault(DateTime.MinValue) 

您可以编写一个通用方法来计算任何类型的Min或Max,如下所示:

 public static T Max(T FirstArgument, T SecondArgument) { if (Comparer.Default.Compare(FirstArgument, SecondArgument) > 0) return FirstArgument; return SecondArgument; } 

然后使用如下:

 var result = new[]{datetime1, datetime2, datetime3}.Max();