-2

im using parse exactl to convert the following string but still give me an error:

Tue Oct 06 2020 15:22:59 GMT 0200 (Central European Summer Time)

here is my convert:

  DateTime frm = DateTime.ParseExact(dtFrom, "yyyy/MM/dd", CultureInfo.InvariantCulture);
moris62
  • 983
  • 1
  • 14
  • 41
  • the second argument of parse exact is a string (or array of strings) defining the format of the date string you give to it, not the one you exept to get out from it. you seem te receive some kind of RFC822 format, try this post: [link](https://stackoverflow.com/questions/284775/how-do-i-parse-and-convert-datetime-s-to-the-rfc-822-date-time-format). – Jochem Van Hespen Oct 07 '20 at 14:45
  • 1
    "parse **exact**" means you need to use an exact format. Your input string does not match the format `yyyy/MM/dd`. – Lasse V. Karlsen Oct 07 '20 at 15:13
  • other idea from this similar question: https://stackoverflow.com/a/46528065/4473044 – an.dr.eas.k Oct 07 '20 at 15:27
  • This issue is not trivial. The ParseExact requires for timezone offset a plus or minus sign. – jdweng Oct 07 '20 at 15:47

1 Answers1

-2

Use Regex :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "Tue Oct 06 2020 15:22:59 GMT 0200 (Central European Summer Time)";
            string pattern = @"^(?'date'.*)(?'sign'.)(?'offset'\d{4})\s(?'ending'\([^)]+\))$";
            Match match = Regex.Match(input, pattern);
            string dateStr = match.Groups["date"].Value;
            string sign = match.Groups["sign"].Value;
            string offset = match.Groups["offset"].Value;
            switch (sign)
            {
                case " ":
                    dateStr = dateStr + " +" + offset;
                    break;
                case "+":
                    dateStr = dateStr + sign + offset;
                    break;
                case "-":
                    dateStr = dateStr + sign + offset;
                    break;
            }
            DateTime date = DateTime.ParseExact(dateStr,"ddd MMM dd yyyy HH:mm:ss \\G\\M\\T zzz", System.Globalization.CultureInfo.InvariantCulture);
        }

    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20