可空类型 - 在 C# 中如何仅比较 DateTime 类型中的日期而非时间?

4
如何在C#中仅比较DateTime类型中的日期而不是时间。其中一个日期将是可空的。我该怎么做?

1
我不明白你的问题。你能否请澄清一下?只需使用 DateTime? < DateTime ? - Soner Gönül
我想比较两个日期时间对象,而不考虑时间...其中一个日期对象是可空类型。 - vmb
您需要处理不同的时区、夏令时转换等吗? - Lasse V. Karlsen
7个回答

6
DateTime val1;
DateTime? val2;

if (!val2.HasValue)
    return false;

return val1.Date == val2.Value.Date;

或者三元运算符:return val2.HasValue ? val1.Date == val2.Value.Date : false; - Dmitry Bychenko
@DmitryBychenko - 这里似乎三目运算符有点繁琐。不如直接写成 return val2.HasValue && val1.Date == val2.Value.Date; ? - Chris Dunaway

2
您可以使用DateTime对象的Date属性。
Datetime x;
Datetime? y;

if (y != null && y.HasValue && x.Date == y.Value.Date)
{
 //DoSomething
}

2
如果y为空,则失败。 - Tim Schmelter

0

这里使用短路来避免比较,如果可空日期为null,则使用DateTime.Date属性确定等价性。

bool Comparison(DateTime? nullableDate, DateTime aDate) {
    if(nullableDate != null && aDate.Date == nullableDate.Value.Date) {
        return true;
    }

    return false;
}

0
bool DatesMatch(DateTime referenceDate, DateTime? nullableDate)
{
    return (nullableDate.HasValue) ? 
        referenceDate.Date == nullableDate.Value.Date : 
        false;
}

0

如果你想要一个真正的比较,你可以使用:

    Datetime dateTime1
    Datetime? dateTime2

    if(dateTime2.Date != null)
       dateTime1.Date.CompareTo(dateTime2.Date);

希望能有所帮助...


0

这里唯一具有挑战性的方面是您想要一个既是DateTime又可为空的东西。

以下是标准DateTime的解决方案:如何在C#中仅比较日期而不是时间?

if(dtOne.Date == dtTwo.Date)

对于可空类型,这只是一个选择问题。我会选择使用扩展方法。

class Program
{
    static void Main(string[] args)
    {
        var d1 = new DateTime(2000, 01, 01, 12, 24, 48);
        DateTime? d2 = new DateTime(2000, 01, 01, 07, 29, 31);

        Console.WriteLine((d1.Date == ((DateTime)d2).Date));

        Console.WriteLine((d1.CompareDate(d2)));
        Console.WriteLine((d1.CompareDate(null)));

        Console.WriteLine("Press enter to continue...");
        Console.ReadLine();
    }
}

static class DateCompare
{
    public static bool CompareDate(this DateTime dtOne, DateTime? dtTwo)
    {
        if (dtTwo == null) return false;
        return (dtOne.Date == ((DateTime)dtTwo).Date);
    }
}

你可以通过 dtTwo.Value.Date 获取日期,而不是强制转换 dtTwo。 - Marcobdv

0
你可以创建一个类似下面的方法,按照.NET框架比较的返回值规则,当左侧较小时返回-1,日期相等时返回0,右侧较小时返回+1:
    private static int Compare(DateTime? firstDate, DateTime? secondDate)
    {
        if(!firstDate.HasValue && !secondDate.HasValue)
            return 0;
        if (!firstDate.HasValue)
            return -1;
        if (!secondDate.HasValue)
            return 1;
        else 
            return DateTime.Compare(firstDate.Value.Date, secondDate.Value.Date);
    }

当然,更好的实现方式是为此创建一个扩展方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接