This question already has an answer here:
- ToLocaleDateString() changes in IE11 5 answers
I've ran into a possible bug with IE where calling the JavaScript .length
function returns a value that is off by 1 if/when the string was derived from .toLocaleString()
.
var d = new Date();
var locale = navigator.language;
var month = d.toLocaleString(locale, { month: "long"});
// month.length will return the length of the month string +1
//(eg: if month = "March", month.length will return 6.)
Interestingly, the code example of above will return true (in IE) for the following: (month[0] should be "M")
month[0] == "";
month[1] == "M";
month[2] == "a";
month[3] == "r";
month[4] == "c";
month[5] == "h";
In my particular case, this is causing a problem where I need to .slice()
the month. Example: If the month is March, then IE will return "Ma" for month.slice(0,3)
instead of "Mar".
Is this a known bug with IE? Is there a fix and/or workaround for this problem?
Run this fiddle in IE and Chrome/Firefox/Safari and notice how the month.length
is wrong in IE.
My Environment:
OS: Win Server 2012 R2
IE Version: 11.0.9600.18231 (Update Versions: 11.0.29)
Locale: English/US
So, I stumbled upon this post toLocaleDateString error in IE 11
It appears it is caused by the toLocaleDateString function added extra LTR and RTL characters in IE11. One of the comments gave a regex replace function that is working for me.
Try adding that after you perform the
.toLocaleDateString()
and it should work. It worked for me.Just another reason for us to despise IE.