Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime.ParseExact "String was not recognized as a valid DateTime" error

Tags:

c#

datetime

Why i can't parse a string like this:

DateTime date = DateTime.ParseExact("‎23.‎02.‎2016 08:59:35", 
                  "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture);

It is throwing an exception

String was not recognized as a valid DateTime.

I really don't understand.

like image 525
Trax Avatar asked Aug 03 '16 10:08

Trax


People also ask

What is valid DateTime format?

Use the yyyy-MM-ddTHH:mm:ss. SSS+/-HH:mm or yyyy-MM-ddTHH:mm:ss. SSSZ formats to specify dateTime fields. yyyy is the four-digit year.


2 Answers

There are some zero-width Unicode characters in your strings. If you remove them it will work:

DateTime.ParseExact("23.02.2016 08:59:35",
    "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture)
like image 71
Eli Arbel Avatar answered Oct 17 '22 14:10

Eli Arbel


Beware beware the &nbsp non-breaking-space it looks like a space but isn't. You might have one of these between your date and time.... Especially if your pulling from a html document...Ohh the pain, the pain. The non-breaking-space also gets treated as whitespace in a regex and pass through undetected.

text = text.Replace('\u00A0',' ');
like image 39
andrew pate Avatar answered Oct 17 '22 16:10

andrew pate