0

I have a function to convert a date string with a specific format into a JS Date Object :

// param userInputBirthdate is a string with this format `dd.mm.yyyy`
function dateObjFromCHString(userInputBirthdate){
  var paramDate = userInputBirthdate.split('.').reverse().join('-');
  return new Date(paramDate);
}

when the user fill the birthDate input, the date object is created successfully by calling this function.

But now in my unit tests, I simulate the string given by the user with this code (I have to calculate the date like this for personal reasons, so please don't advise to simply write a string date constant) :

var localDateOptions = {month:'2-digit',year:'numeric',day:'2-digit'};
var today = new Date();
olderDate.setDate(today.getDate()-(25*365));  //25 years ago
olderDate = olderDate.toLocaleDateString('fr-CH',localDateOptions).replace(/\//g,'.');//return something like 23.03.1985

but now when I convert it with the function :

dateObjFromCHString(olderDate); //returns [date] Invalid Date in IE11

I get an "Invalid Date" with IE (tested with IE11 edge mode), but everything works fine with FF, Chrome or Opera... Can somebody tell me what is IE's problem ?

Note: I saw the other SO threads about this problem and the recommandation to use the format yyyy-mm-dd hh:mm:ss for the new Date param, but as it works with new Date('2012-03-11'), I want to know why the unit test code does not work.

ylerjen
  • 4,109
  • 2
  • 25
  • 43

1 Answers1

0

I found the problem with the help of this question : ToLocaleDateString() changes in IE11

If you log every char of the tolocalDateStringresult separatly, you will see that there is unshown characters that aren't displayed when logging the full result.

Ex:

var str=(new Date).toLocaleDateString();
for(var i=0;i<str.length;i++)
console.log(i,str.charCodeAt(i),str.charAt(i))

Will output something like this with IE11 :

0  8206 ‎
1  49    1
2  57    9
3  8206
‎4  46    .
5  8206 ‎
6  48    0
7  53    5
8  8206 ‎
9  46    .
10 8206 ‎
11 50    2
12 48    0
13 49    1
14 53    5

As you can see there is 5 non-visible characters (charcode = 8206) that will break my conversion into date from a toLocaleDateString result.

I solved the problem using the momentjs library to handle all the date functions in my unit tests.

Community
  • 1
  • 1
ylerjen
  • 4,109
  • 2
  • 25
  • 43