dev
dev

Reputation: 19

toLocaleDateString() in IE returns a 14 character string - is it a bug

Please look at http://jsbin.com/mehowehase/1/edit?html,js,console

var dt = new Date();
var x = dt.toLocaleDateString();
console.log("length : "+x.length);
var arr = x.split("/");
console.log("month : "+parseInt(arr[0],10));

In the above the length of x is 14 in IE but 9 in other browsers. Also the month value comes as NaN. Is this a bug in IE. How can we fix this.

Upvotes: 0

Views: 858

Answers (4)

Vlad Bezden
Vlad Bezden

Reputation: 89725

This is a bug in IE11. You can find temporarily solution for this issue here

Basically you need to replace U+200E (LEFT-TO-RIGHT MARK).

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

Upvotes: 3

Robert McKee
Robert McKee

Reputation: 21477

It is not a bug. IE's toLocaleDateString method returns a unicode string, and your code isn't expecting one. For example, the first character in IE (for me and my locale (en-US)) is 8206, which is the left-to-right mark character, which is also why your parseInt is failing. The entire sequence is

8206,49,49,8206,47,8206,51,8206,47,8206,50,48,49,53

which is 14 characters long and looks like "11/3/2015"

Why aren't you doing this:

var dt=new Date();
var day=dt.day;
var month=dt.month;
var year=dt.year;

Upvotes: 0

dev
dev

Reputation: 19

Solved it like this

var day = arr[1];
var month = arr[0];
var year = arr[2];
if(isNaN(month)){
   var curr = "";
   for (var i = 0; i < month['length']; i++) {
      if(!isNaN(month.charAt(i)))
         curr += parseInt(month.charAt(i));
   }
   month = curr;
}
console.log("month: "+parseInt(month,10));

Upvotes: 0

John Biddle
John Biddle

Reputation: 233

For me, on Chrome 42.0 the string output of toLocaleDateString is "11/3/2015". For Internet Explorer 11.0.9, it is "Tuesday, November 03, 2015". You'll have to change your parsing to read the format that Internet Explorer outputs, it's has all of the information you need, just in a different format.

Upvotes: 0

Related Questions