Datetime "Null" = 01/01/0001

Asked

Viewed 4,409 times

2

How to treat a field DateTime that comes as "null" (I know that DateTime can’t be null) of a legacy basis?

Consulting a WebService it returns a field DateTime as 01/01/0001 (no value) in the case of a string empty or null there is an "elegant" way to treatIsNullOrEmpty

My question is: What is the best way to treat a DateTime "null", ie with value 01/01/0001

  • 1

    You can Try Comparing it with DateTime.MinValue.Date.ToString("d") if think that is the Elegant?

  • Appreciate your comment, I’ll Try it.

  • @rubStackOverflow I’m not sure I understand what you want. The answer already does what you want. Or isn’t that right? Do you want the factor to be null? Do you need this? Do you only need to do something different if you have this date? Is it certain that this date will always represent invalid data? If you give a larger context of how you are using, you may have a better solution.

  • 1

    Yes, the answer does what I want seen that DateTime.MinValue may be replaced by 01/01/0001. I didn’t want to have to compare the date with 01/01/0001 (ex: minhaData == 01/01/0001). I don’t want the date to be null, the null date always comes with 01/01/0001 webservice.

1 answer

6


You can compare the date with the DateTime.MinValue to find out if the date was instantiated without value:

DateTime suaData = new DateTime();

if (suaData == DateTime.MinValue)
{
    //operação
}

And remember that the DateTime can be used as nullable. For this just add one ? after the type, in which case the verification of != null or use the attribute HasValue as below:

DateTime? suaData = null;

if (!suaData.HasValue)
{
    //operação
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.