5

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?

4
  • Does your database actually store null for your column? Commented Oct 17, 2012 at 6:49
  • 1
    No the database stores "01-01-1900" if the value is null. Commented Oct 17, 2012 at 6:53
  • 1
    Maybe you should have the database store null instead of "01-01-1900"? Commented Oct 17, 2012 at 7:11
  • I second Torben. but then again if your database will never use that date then go ahead - no point doing much workaround for a little thing that doesn't bother your app. Commented Oct 17, 2012 at 9:03

2 Answers 2

6

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;
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.