Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript date to ASP.NET date: String was not recognized as a valid DateTime

I'm passing a date back to my MVC controller via AJAX using:

date.GetDate().toLocaleDateString();

This will produce a value of "4/5/2014"... When I try and convert this inside my controller using:

DateTime myDate = DateTime.ParseExact(request.Params["myDate"], "dd/MM/yyyy", CultureInfo.InvariantCulture);

I get "String was not recognized as a valid DateTime." Which makes sense because the format of the string isn't correct... When I hardcode the string to: "04/05/2014" it will fix my issue.

Is there anyway to fix the format coming from javascript without have to rip the string apart into day, month, year and reassembling it in the proper format?

Any advice would be much appreciated!

Thank you

Additional info:

string myRequestDate = request.Params["myDate"];
string myViewBagDate = ViewBag.MyDate;

//This line passes
DateTime date1 = DateTime.ParseExact(myViewBagDate, "d/M/yyyy", CultureInfo.InvariantCulture);

//This line fails...
DateTime date5 = DateTime.ParseExact(myRequestDate, "d/M/yyyy", CultureInfo.InvariantCulture);

When I add a watch on both of the string variables the values are identical in every way I can see but for some reason the second line fails...

So when I look at the myRequestDate as a char array I see there is a bunch of stuff in there that doesn't look like a date at all...

enter image description here

like image 872
Hidan Avatar asked Jun 11 '26 01:06

Hidan


1 Answers

Character 8206 (U+200E) is the Unicode LEFT-TO-RIGHT MARK (which is invisible). Try to figure out where it's coming from and remove it at the source.

As a workaround, you can strip out those characters before you parse the date:

myRequestDate = myRequestDate.Replace("\u200E", "");
DateTime date5 = DateTime.ParseExact(myRequestDate, "d/M/yyyy", CultureInfo.InvariantCulture);
like image 198
Michael Liu Avatar answered Jun 12 '26 16:06

Michael Liu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!