Search code examples
javascriptdatelocale

Javascript toLocalDateString outputs different format on windows vs mac


I'm using Javascript's toLocalDateString method to get the date of the user on their local system time. However the output format of the function is different across windows and mac (using chrome browsers on both):

On Windows

enter image description here

On Mac

enter image description here

As you can see on windows we get format m-dd-yyyy whereas on mac it's dd-mm-yyyy. This is causing issues in my code as I need to display it in a common format using substr on the resulting output and fetching year, date and month separately.

Is there any way to force this to output in one particular format only or is there any other reliable way to get system's local date (I only need date not the time)


Solution

  • You will have to pass locals argument as below:

    // US English uses month-day-year order

    console.log(date.toLocaleDateString('en-US'))
    

    // British English uses day-month-year order

    console.log(date.toLocaleDateString('en-GB'))
    

    Check reference link - toLocaleDateString