Search code examples
c#datetimeparsingxrm

C# Parsing DateTime Unable to Convert String to DateTime


I followed the string output of my date variable, and parsed according to the format, but still encountered an Format Exception.

May I know what should I change?

string DOB = retrieved.Entities[i].GetAttributeValue<AliasedValue>("Contact.birthdate").Value.ToString();
//output: 4/13/2018 12:00:00AM

DateTime DOB_formatted = DateTime.ParseExact(DOB, "MM/dd/yyyy", null);
//System.FormatException

Resolution: Convert Object to DateTime

DateTime DOB_formatted = Convert.ToDateTime(retrieved.Entities[i].GetAttributeValue<AliasedValue>("Contact.birthdate").Value);

Solution

  • ParseExact() requires a perfect match. The MM/dd/yyyy format string would require 04/13/2018, but the value is 4/13/2018 12:00:00AM. You want M/d/yyyy hh:mm:sstt, and you should confirm day values don't have leading zeroes. There's also an overload that takes an array of format strings, if you can't trust the data source to be consistent.

    Finally, per the comments, the compile-time type of Value is Object. But what about run-time? There's still a good chance the run-time type is already a DateTime value, and all you need to do is cast it. Because of internationalization/culture issues, converting to string and then re-parsing back to DateTime is suprisingly expensive. Avoiding those conversions will save the computer a ton of work, and really help performance.