0

I want to convert String into DateTime. Everything is correct but don't know why I am getting this error;

String was not recognized as a valid DateTime

string  dtf = hdnFromDate.Value;

(While debugging I can see dtf value is Sun Dec 13 2020 00:00:00 GMT+0300 (Arab Standard Time)) and I am trying to convert into DateTime But no success I am converting in this way

DateTime date = DateTime.ParseExact(dtf, "dd/MM/yyyy", null); 

I also try like this

DateTime dt= DateTime.ParseExact(dtf, 
                  "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(Arab Standard Time)'", 
                  CultureInfo.InvariantCulture);

Where I am doing wrong?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
cd d
  • 73
  • 6

1 Answers1

0

Reference to DateTime.ParseExact Method

Converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly or an exception is thrown.

So your datetime string should like this otherwise you will get exception

Mon Dec 14 2020 14:42:46 GMT+08:00 (Arab Standard Time)

or

Mon Dec 14 2020 14:42:46 GMT+0800 (Arab Standard Time)

You can try this to get what kind of string you need

Console.WriteLine(
   DateTime.Now.ToString("ddd MMM dd yyyy HH: mm:ss 'GMT'K '(Arab Standard Time)'", 
   CultureInfo.InvariantCulture)
);

If your string have whitespace li

Mon Dec 14 2020 14: 42:46 GMT+08:00 (Arab Standard Time)

Yoo can try

Console.WriteLine(
   DateTime.Now.ToString("ddd MMM dd yyyy HH: mm:ss 'GMT'K '(Arab Standard Time)'", 
   CultureInfo.InvariantCulture,
   DateTimeStyles.AllowWhiteSpaces)
);
MichaelMao
  • 2,596
  • 2
  • 23
  • 54