Internet Explorer toLocaleDateString Formatting


I recently ran into an issue in an Angular app when trying to pass a date to an API using Internet Explorer. I was using toLocaleDateString() to format it as a short date, but when the app runs in IE, it messes up the formatting.
Here's an example of the code I'm running:
this.http.get(
`https://fakeapiurl/?date=${this.currentDate.toLocaleDateString()}`
);
Here's how it looks in Chrome when inspecting the outgoing call in the network tab, which is just what I would expect: https://fakeapiurl/?date=1/13/2020
.
Here is how it comes out in IE: https://fakeapiurl/?date=â1â/â13â/â2020
.
This was getting interpreted by our API as ?1?/?13?/?2020
, which of course is not a valid date and would throw an error.
Solution
The solution we went with was to format the outgoing date using momentJS. We were already using momentJS for other date manipulation so it was an easy fix.
To format it we used: moment(this.currentDate).format('M/D/YYYY')
You could of course do it with native javascript by building the string manually, using something like this:
this.currentDate.getMonth() +
1 +
'/' +
this.currentDate.getDate() +
'/' +
this.currentDate.getFullYear();
Note that you have to add 1 to getMonth because it returns numbers 0-11 instead of 1-12.