Search code examples
c#datetimedatetime-conversion

Conversion failed with "date" was not recognized as a valid DateTime


I try convert the date with below code,

string currDate = @"Fri, 10 Jul 2020 05:48:28 -0500 (CDT)";
DateTime convDate = Convert.ToDateTime(currDate);

Console.WriteLine("COnverted Date :: " + convDate.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK", CultureInfo.InvariantCulture));

But, it failed with below error message,

  Unhandled exception. System.FormatException: String 'Fri, 10 Jul 2020 05:48:28 -0500 (CDT)' was not recognized as a valid DateTime.

It would be nice anyone help on this.

Thanks,


Solution

  • You can put the (CDT) into single quotes in format string to ignore it while parsing using DateTime.ParseExact method

    string currDate = @"Fri, 10 Jul 2020 05:48:28 -0500 (CDT)";
    DateTime convDate = DateTime.ParseExact(currDate, "ddd, dd MMM yyyy HH:mm:ss K '(CDT)'", CultureInfo.InvariantCulture);
    

    It returns you a local date time, in my end output is

    Converted Date :: 2020-07-10T13:48:28.000+03:00

    To get the UTC one you can pass DateTimeStyles.AdjustToUniversal parameter to ParseExact method. It gives you

    Converted Date :: 2020-07-10T10:48:28.000Z