0

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,

Ramachandran
  • 103
  • 12
  • Use `DateTime.TryParseExact` – TheGeneral Jul 14 '20 at 06:25
  • Ya.. Thanks for your response. I tried with this DateTime convDate = DateTime.ParseExact(currDate, "yyyy-MM-dd'T'HH:mm:ss.fffK", CultureInfo.InvariantCulture);. But, still the same error. – Ramachandran Jul 14 '20 at 06:27
  • The pattern does not match. That's all. Try to Format a date with that pattern. you will find it will look totally different. – Fildor Jul 14 '20 at 06:32
  • 1
    Does this answer your question? [Converting a String to DateTime](https://stackoverflow.com/questions/919244/converting-a-string-to-datetime) – Pavel Anikhouski Jul 14 '20 at 06:35
  • 1
    Try string `Fri, 10 Jul 2020 05:48:28 -05:00` without (CDT) – mrNone Jul 14 '20 at 06:36

1 Answers1

4

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

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
  • Thanks for your comments. Actually, I got this date format from google email. So, i receive different format every time. For example, sometime I got the date like this, Tue, 26 May 2020 11:15:19 GMT – Ramachandran Jul 14 '20 at 06:56
  • 1
    @Ramachandran For GMT time you can use `ddd, dd MMM yyyy HH:mm:ss 'GMT'` format string. If you have a different format every time, you might remove the timezone prefix from string first, then parse it – Pavel Anikhouski Jul 14 '20 at 07:21
  • Ya... Thank you.. Thanks for your help. – Ramachandran Jul 14 '20 at 07:42