0

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.

dev
  • 19
  • 1

4 Answers4

3

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

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.

John Biddle
  • 233
  • 1
  • 10
  • 1
    Thanks for your reply John. Internet explorer too gives me "11/3/2015". How can we handle this so the same piece of code works in every browser. – dev Nov 03 '15 at 23:22
0

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;
Robert McKee
  • 21,305
  • 1
  • 43
  • 57
  • Is there a way we can drop or replace these 8206 so it behaves same as in other browsers. Thanks. – dev Nov 03 '15 at 23:26
  • You can output it just fine. If you want to know the month, why are you converting a Date to a string and then trying to parse it? – Robert McKee Nov 04 '15 at 01:35
0

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));
dev
  • 19
  • 1
  • This will only work if your system format is set to short dates AND you are using mm/dd/yyyy date format. If you want to know the month, just ask the dt object -- `var month=dt.month;` – Robert McKee Nov 04 '15 at 01:38