parseInt not working with data from an Array created from a spitted Date inside Angularjs controller

682 views Asked by At

I have a date that I am converting to LocaleDateString and then splitting it into an array inside an angulrajs controller. When I try to convert to int the elements in the array I get NaN. The characters in the array are numbers but the parse is not working.

How can I parse that data properly?

Code:

var dateLocal = $scope.startDate.toLocaleDateString(); //Has this ‎6‎/‎5‎/‎2015
var dateSplitted = dateLocal.split("/"); //Has [6,5,2015]
var month = parseInt(dateSplitted[0]);  //HERE If I use parseIntI get NaN originally it has 6
var day = dateSplitted[1];//Has 5
var year = dateSplitted[2]; Has 2015

I want to be aple to convert to string month day and year.

3

There are 3 answers

9
Oriol On BEST ANSWER

You rely on toLocaleDateString, which is implementation dependent:

This function returns a String value. The contents of the String are implementation-dependent

The problem is that your browser returns a string with some left-to-right marks (U+200E).

See the difference:

var str1 = "6", // "\u0036"             <-- OK
    str2 = "‎6‎"; // "\u200e\u0036\u200e" <-- Your "corrupted" string
parseInt(str1); // 6
parseInt(str2); // NaN

So you shouldn't trust the value returned by that method. Instead, use date methods to get the day, month and year.

0
Harsha Kuchampudi On

I tried out your code, and it seemed to work fine for me. For your dateLocal, I just replaced your value with var dateLocal = new Date().toLocaleDateString(); because I didn't know what value was loaded from your scope. When I did this, the code loaded fine, so you may want to double check the nature of the variable you are loading from the scope.

2
tavnab On

This doesn't answer why you are getting NaN in your code, but instead of converting the date object to a string and parsing the parts, you can get the parts of the date directly using Date.prototype.getMonth(), Date.prototype.getDate() (day-of-month), and Date.prototype.getFullYear().