繁体   English   中英

比较可为空的日期时间对象

[英]Compare nullable datetime objects

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

我已经尝试过:

DateTime.Compare(birthDate, hireDate);

这给出了一个错误,也许它需要System.DateTime类型的日期,而我有 Nullable 日期时间。

我也试过:

birthDate > hiredate...

但结果并不如预期......有什么建议吗?

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

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<DateTime?>
{
    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<T>(this T? left, T? right)
        where T : struct, IComparable<T>
    {
        return left.GetValueOrDefault().CompareTo(right.GetValueOrDefault());
    }
}

你会在哪里使用它

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

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

var equal = Nullable.Compare<DateTime>(birthDate, hireDate);

正如@Vishal 所说,只需使用Nullable<T>重写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.Equals(hireDate)

并在比较后做你的事情。

或者,使用

object.equals(birthDate,hireDate)

我认为您可以按以下方式使用该条件

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

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

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

然后使用如下:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM