简体   繁体   English

比较Nullable DateTime变量的默认值

[英]Compare Nullable DateTime variable for default value

In my C# code, I have a DateTime? 在我的C#代码中,我有一个DateTime? variable. 变量。 While getting the values from database it can be null or can have some date/time value. 从数据库获取值时,它可以为null或可以具有某个日期/时间值。

On the front end side I don't want to get the default value (01-01-1900 12:00:00 am). 在前端,我不想获得默认值(01-01-1900 12:00:00 am)。 Whats the best way to compare my date variable for this default date? 什么是比较我的日期变量这个默认日期的最佳方法?

You can create a const: 你可以创建一个const:

static readonly DateTime DefaultDateTime = new DateTime(1900, 1, 1, 0, 0, 0);

and then compare this way: 然后比较这种方式:

DateTime? myVariable = returnedFromDb == DefaultDateTime ? default(DateTime?) : returnedFromDb;

You can have an extension method, something like this: 你可以有一个扩展方法,如下所示:

public static class DateTimeExtensions
{
    static DateTime SQL_DEFAULT = new DateTime(1900, 1, 1);

    public static bool IsDefaultValue(this DateTime dateTime)
    {
        return dateTime == SQL_DEFAULT;
    }
}

And then just test the value: 然后只测试值:

var isDefault = myDate.IsDefaultValue(); var isDefault = myDate.IsDefaultValue();

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

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