Matt Hintzke
Matt Hintzke

Reputation: 8004

IE charset encoding issue with JavaScript Date functions

Could someone please explain why IE has a bug when trying to use String functions on a Date function that uses the "Locale"? I think it has something to do with encoding of the characters.

Check this out jsFiddle in both IE and Chrome and you will see that in Chrome we get 4 (the correct index) and in IE we get 8. Does this have to do with ascii vs. unicode? If so, should this be a bug in IE?

var date = new Date();

var str = date.toLocaleTimeString();
jQuery('#a').text(str);

jQuery('#b').text(str.lastIndexOf(":"));

str = date.toTimeString();
jQuery('#c').text(str);
jQuery('#d').text(str.lastIndexOf(":"));

Screen shot of IE 11 jsFiddle output

Screen shot of IE 11 jsFiddle output

Upvotes: 1

Views: 837

Answers (2)

c-smile
c-smile

Reputation: 27470

By definition Date.toLocaleTimeString() produces output according to user's preferences/defaults.

So the result (position of : ) can vary on different platforms, locales and even time of the day.

This is how Korean time looks like for example:

"오후 12:00:00"

Apparently in your case Chrome and IE have different opinion on default locale formatting.

If you have any code that relies on position of : in toLocaleTimeString() it must be refactored to something more reliable.

In some locales/settings toLocaleTimeString() may not contain : at all.

Upvotes: 1

Pointy
Pointy

Reputation: 413996

Here's a modified fiddle. For whatever reason, the IE 11 string has a bunch of extra Unicode "left-to-right mark" characters embedded in it.

The code I added was

var s = '';
for (var i = 0; i < str.length; ++i)
    s  += str.charCodeAt(i) + ' ';
$('#c').text(s);

and an accompanying <h4> like the others.

Also see this other Stackoverflow question on the topic.

Upvotes: 1

Related Questions