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);
ParseExact()requires a perfect match. TheMM/dd/yyyyformat string would require04/13/2018, but the value is4/13/2018 12:00:00AM. You wantM/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
ValueisObject. But what about run-time? There's still a good chance the run-time type is already aDateTimevalue, 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.