Today an API changed and broke this legacy code with the following error:
[System.FormatException: String was not recognized as a valid DateTime.]
The new date take this form: 2020-01-16T14:29:17.9743131Z0
.
public static void Main()
{
var result = "2020-01-16T14:29:17.9743131Z0";
Console.WriteLine("dateTime : {0}", result);
Console.WriteLine("result : {0}", Convert.ToDateTime(result));
}
Neither DateTime.Parse's official documentation nor DateTime.ParseExact's official documentation help me as far as I tried at that point. Lets ask internet.
I searched online and found How to create a .NET DateTime from ISO 8601 format. The first solution with DateTime.Parse
and DateTimeStyles.RoundtripKind
but it failed with the same error. The second solution use DateTime.ParseExact
, custom formats, and DateTimeStyles.None
. 18 formats. None works. The third one rely on the flag DateTimeStyles.AssumeUniversal
. It didnt work all the same.
I also check another link (Given a DateTime object, how do I get an ISO 8601 date in string format?) without success.
How can I handle this format?