IE 11 issue with JavaScript toLocaleDateString() f

2019-07-03 23:19发布

问题:

I am using the JavaScript Date function toLocaleDateString() to format my date to look like 8/13/2014, but for some reason when I try to send this value via an API call by doing a JSON.stringify and then AJAXing the value, IE decides to change the actual value to be ?8?/?30?/?2014.. This obviously causes errors on the back end.

Why does IE do this and how can I fix it?

回答1:

Looks like it's a bug that was introduced in IE 11. IE 11 uses Unicode chars, so what you see is U+200E 'LEFT-TO-RIGHT MARK'

What you can do as a temporary solution to fix this issue is to replace that char. Like this:

console.log((new Date()).toLocaleDateString().replace(/\u200E/g, ''));


回答2:

You should check out the answer here: ToLocaleDateString() changes in IE11

You shouldn't be using a function intended to format something for locale-specific human display and expect the output to be machine parsable. Any of the output of toLocaleString, toLocaleDateString, or toLocaleTimeString are meant for human-readable display only. (As Bergi clarified in comments, toString is also meant for human display, but ECMA §15.9.4.2 says it should round-trip)

Although the function returns a string, it's only human-readable and is never appropriate for machine parsing. I'm not 100% sure what encoding it is for IE, but although it looks like a string, underneath it uses a different encoding.

For date formatting, you may wish to use Moment.js, or just write your own formatting function.