user1537319
user1537319

Reputation:

Error Message as "String was not recognized as a valid DateTime."

My Code:

DateTime? birthDate = DateTime.Parse(filterDictionary.ContainsKey("DOB") ? filterDictionary["DOB"] : string.Empty);

I am getting Error Message as "String was not recognized as a valid DateTime." How to solve this issue. Thanks.

Upvotes: 0

Views: 671

Answers (2)

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

The problem (at least one of them) is that you can't parse an empty string to a DateTime.

Change your line of code to this to move the parsing only when you find the key, and return null instead of parsing when you don't have it:

DateTime? birthDate = filterDictionary.ContainsKey("DOB") ? DateTime.Parse( filterDictionary["DOB"]) : (DateTime?) null;

The other problem might be that your dictionary DOB value is actually not possible to convert to a DateTime. If the above code does not work, please edit your question and post the value in filterDictionary["DOB"] when you get this error.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499810

Well DateTime.Parse is always going to fail when you present it with an empty string.

It's not clear whether the time that you've seen this has been one where there has been data in the dictionary but it's invalid, or whether there's been no data and it's parsing string.Empty. Also note that DateTime.Parse returns DateTime, not DateTime?. If you want the value to be null if the entry wasn't in the dictionary, I'd actually use:

DateTime? birthDate = null;
string dobText;
if (filterDictionary.TryGetValue("DOB", out dobText))
{
    birthDate = DateTime.Parse(dobText);
}

Or perhaps:

string dobText;
DateTime? birthDay = filterDictionary.TryGetValue("DOB", out dobText)
    ? DateTime.Parse(dobText) : (DateTime?) null;

Note that you need to cast at least one of the second or third operands to null here so the compiler can work out the type of the conditional expression.

You should also consider whether a plain call to DateTime.Parse is appropriate:

  • If you know the specific format you're expecting, call DateTime.ParseExact
  • If this is user input, you should probably be using TryParse or TryParseExact
  • If it's not user input, you should probably be specifying a parsing culture of CultureInfo.InvariantCulture
  • If it's direct user input in a GUI, is there a way you can avoid getting it as text in the first place?

Upvotes: 1

Related Questions