简体   繁体   中英

Compare Nullable DateTime variable for default value

In my C# code, I have a DateTime? variable. While getting the values from database it can be null or can have some date/time value.

On the front end side I don't want to get the default value (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:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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