The following piece of code gets the month from a date
object in JavaScript.
const date = new Date(dateValue);
const month = date.toLocaleString('default', { month: 'short' });
For example: if the date is something like 30/07/2019
it will return Nov
.
This works fine in Chrome but fails in Edge browser with error:
SCRIPT5121: SCRIPT5121: Locale 'default' is not well-formed
My Edge browser version is 41.16299.1004.0
Here's a jsfiddle: https://jsfiddle.net/1dwcv9xu/1
As per MDN, date.toLocaleString
is fully supported in Edge: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString#Browser_compatibility.
Also I couldn't find this error code in the MSDN docs for Edge: https://docs.microsoft.com/en-us/microsoft-edge/devtools-guide/console/error-and-status-codes.
Is there a way to fix this or any alternate approach to get the month in mmm
format?
As per the suggestion from Phuzi, i changed to
date.toLocaleString('en-GB', { month: 'short' })
then it started working in IE 11 But it doesn't work in IE 10. So i went with Classic Javascript approach
Might seem crazy, but using undefined
rather than default
resolves the error in IE11 and works in all the major browsers that I've checked (Mac/Windows).
const date = new Date(dateValue);
const month = date.toLocaleString(undefined, { month: 'short' });
The arguments locales
and options
are not supported by all browser versions. Newer versions of Edge already support the "default"
value, but older versions do not (despite supporting the parameters). I am not sure which version started to support the "default"
value.
According to this page, "if the locales argument is not provided or is undefined, the runtime's default locale is used". Thus you could try date.toLocaleString(undefined, { month: 'short' });
. Such value is supported by Edge.
The topic requires some more research. I stopped now once you answered the question with another solution. But if you have some more time give a try and share back your results with us.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With