Recently I posted about a method I use in JavaScript (Angular specifically) to transform posted Date objects to transmit the local DateTime. It’s a simple method that uses JavaScript’s “toLocaleString” method while intercepting POST requests. Everything worked fine except when IE11 was introduced into the equation.
It’s a curious bug because basically, you can run this code in IE11 and it will fail:
var dateStr = new Date().toLocaleString(); var date = new Date(dateStr);
That code works fine in Chrome, and probably the rest of the world, though. Upon examination of the string created, I didn’t see anything wrong. Not only could IE11’s JavaScript engine not parse its own output, my back-end ASP.NET C# code couldn’t desalinize the string either.
Fortunately, I stumbled upon another blog post that illustrated that the problem was that IE11’s “toLocaleString” method was outputting, effectively, hidden unicode characters within the string.
My simple solution, which fixes both the JavaScript parsing issue and the ASP.NET deserialization issue, is to remove all non-ASCII characters with a Regular Expression.
var dateStr = new Date().toLocaleString().replace(/[^A-Za-z 0-9 \.,\?""!@#\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~]*/g, ''); var date = new Date(dateStr);