Search code examples
javascriptmicrosoft-edgeparseint

Why is ParseInt() returning NaN on Microsoft Edge?


Go to the console of Microsoft Edge and run the following JavaScript:

current_date = new Date().toLocaleDateString("en-CA",{timeZone: "America/Los_Angeles"});
a = current_date.substring(0,current_date.indexOf('-'));
console.log(parseInt(a));

I get a NaN; do you? I tried this same code in the console of Chrome and Firefox and they all yield "2019" when parseInt(a) is run.

1) Why is this happening?

2) How can I parse the "a" variable and convert it into an integer in Microsoft Edge?

screenshot of console output


Solution

  • I saw the same issue when running the snippet in Edge.

    Edge apparently adds some hidden formatting to the string when using ToLocaleDateString() so that has to be cleared before using either parseInt() or Number() like .replace(/\u200E/g, '');

    Reference

    current_date = new Date().toLocaleDateString("en-CA",{timeZone: "America/Los_Angeles"}).replace(/\u200E/g, '');
    a = current_date.substring(0,current_date.indexOf('-'));
    console.log(parseInt(a));
    console.log(Number(new Date().toLocaleDateString("en-GB", {day: "numeric"}).replace(/\u200E/g, '')));