3

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?

Matt Hintzke
  • 7,744
  • 16
  • 55
  • 113
  • Looks like you've got some character encoding issues. Exactly what they are is hard to say; make sure your pages, your server, and your database are all in agreement as to what character encoding is in use. – Pointy Aug 13 '14 at 19:33
  • Not sure where this would be set though? All should be UTF-8 I believe. Do you think it is `JSON.stringify`? – Matt Hintzke Aug 13 '14 at 19:46
  • The problem wouldn't be caused by `JSON.stringfy`, though it is not clear how and why you're doing that. You can use the browser's "Network" tab in the developer console to look at the HTTP headers. – Pointy Aug 13 '14 at 19:49
  • Yeah I have been looking at the headers and the content-type is `application/json; charset=utf-8`.. We use `JSON.stringify` because we have an ASP .NET backend that uses JSON Deserializer to map the JSON to a class – Matt Hintzke Aug 13 '14 at 20:00
  • 1
    the page must be set to utf-8, not just the ajax – dandavis Aug 13 '14 at 20:02
  • It already is set to utf-8 – Matt Hintzke Aug 13 '14 at 21:06
  • 1
    Right now my only solution was to convert all of my dates to be in the form `mm/dd/yyyy` which would make `8/13/2014` be `08/13/2014`...This is a workaround but still doesn't answer the question why this was occurring in the first place – Matt Hintzke Aug 13 '14 at 21:41

2 Answers2

4

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, ''));
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
0

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.

Community
  • 1
  • 1
Nelson Yeung
  • 3,262
  • 3
  • 19
  • 29