Search code examples
c#.netdatetimewindows-phone

Strange error when parsing string to date?


When I try to parse date like this:

DateTime t1 = DateTime.ParseExact("August 11, 2013, 11:00:00 PM", "MMMM dd, yyyy, hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);

It works correctly but when I do thing like this :

string s ="‎August ‎11, ‎2013, ‏‎11:00:00 PM";
DateTime t = DateTime.ParseExact(s, "MMMM dd, yyyy, hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);

I get this error :

An exception of type 'System.FormatException' occurred in mscorlib.ni.dll but was not handled in user code


Solution

  • Because your string

    string s = "‎August ‎11, ‎2013, ‏‎11:00:00 PM";
    

    Includes 0x200e(8206) character at the beginning and end of August. You can see it easily by

    var chars = s.ToCharArray();
    

    Seems to be a copy+paste problem

    You can remove those chars by:

    var newstr = new string(s.Where(c => c <128).ToArray())