-4

I have a datetime as string 2020-05-14T13:37:49.000+0000, I need convert to DateTime using C#.

Which is the valid format ? yyyy-MM-ddTHH:mm:ss.FFFZ wrong for me

    [TestMethod]
    public void DateTime_Iso8601_is_ok()
    {
        var f = "2020-05-14T13:37:49.000+0000";
         string format = "yyyy-MM-ddTHH:mm:ss.FFFZ";

        DateTime d;
        DateTime.TryParseExact(f, format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out d);


        //FileHelpers.ConvertException: Error Converting '2020-05-14T13:37:49.000+0000' to type: 'DateTime'.  
        //There are more chars in the Input String than in the Format string: 'yyyy-MM-ddTHH:mm:ss.FFFZ'
    }
Kiquenet
  • 14,494
  • 35
  • 148
  • 243
  • related : [Converting between European and US dates with +0000 on the end](https://stackoverflow.com/questions/43780795/), [Convert 2015-06-01T02:31:00+0000 to DateTime object c#](https://stackoverflow.com/questions/30565262/), https://stackoverflow.com/questions/16521777/converting-this-into-a-date-time-format-c-sharp https://stackoverflow.com/questions/60408557/c-sharp-date-time-parse-from-fri-feb-21-230758-0000-2020 – xdtTransform Jun 15 '20 at 14:14
  • @xdtTransform not same `2020-05-14T13:37:49.000+0000` than `2020-05-14T13:37:49+0000` – Kiquenet Jun 15 '20 at 21:20
  • During your debug you must have try `"yyyy-MM-ddTHH:mm:ss.FFF"` against a date without the +0000 part. Identifying the issue to be the last +0000. This part is a common question because MSDN state that z, zz, zzz format will respectively display +6, +06, +06:00. The documetation state nothing about the +0000 without `:`. It's almost a natural error – xdtTransform Jun 16 '20 at 07:32

2 Answers2

4

You should use K format specifier, since it represents timezone offset

string format = "yyyy-MM-ddTHH:mm:ss.FFFK";

or zzz, which means signed timezone offset

string format = "yyyy-MM-ddTHH:mm:ss.FFFzzz";

You also might change DateTimeStyles to AdjustToUniversal to get 5/14/2020 1:37:49 PM date, otherwise it'll be adjusted to local time

DateTime d;
DateTime.TryParseExact(f, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out d);
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
-2

You need to add single quotes for T and Z like

DateTime parsedDateTime;    
DateTime.TryParseExact(obj, "yyyy-MM-dd'T'HH:mm:ss'Z'", null, System.Globalization.DateTimeStyles.None, out parsedDateTime);
return parsedDateTime;
Rachit Tyagi
  • 658
  • 1
  • 9
  • 24