Using Intl.DateTimeFormat.format
function you can generate a date string formatted for a specific locale. The options passed to the Intl.DateTimeFormat.format()
function allow to know some things about the format, for example if the year is two digit or four digit, but some things are not known, for example the separator used or the order of the year, month and day elements.
Trying to parse that string back to a Date
object is not always possible using Date.parse
.
For example this code fails for the spanish locale and works for the english:
const date = new Date(2020, 10, 28);
const regionEs = new Intl.DateTimeFormat('es', { timeZone: 'UTC' });
const regionEn = new Intl.DateTimeFormat('en', { timeZone: 'UTC' });
const stringEs = regionEs.format(date); // "28/11/2020"
const stringEn = regionEn.format(date); // "11/28/2020"
const parseEs = new Date(Date.parse(stringEs)); // Error -> Trying to set month to 28
const parseEn = new Date(Date.parse(stringEn)); // Ok
But it could be easy if the format template used to generate the string could be obtained from Intl
: something like "dd/mm/yyyy"
. This way the string could be safely splited into parts that could be used to build a Date
object. The problem is that it seems not possible to get that information from Intl.DateTimeFormat
.
The [Intl.resolvedOptions()][1]
method does not provide any help since it just provides back the options passed on the constructor plus defaults.
Question
Is there any way to parse back a string formatted with Intl
to a Date
object without using moment.js
or any other external library?
My use case
I'm using a date-time component that accepts a format and parse functions to handle the dates. When the user selects a date using the calendar controls of the date time input there is no problem and the format function uses Intl
to format it according to the locale and a set of format options.
Sometimes the user edit the date displayed manually. If spanish locale is used he can see "27/11/2020"
date displayed and he made decide to change the day to "28/11/2020"
. This will fail because Date.parse()
can not parse this date (see above). This may get worse in other locales.
I'm trying to avoid including an external date library, but don't see a way to overcome this.
I know that the user may edit the date in any arbitrary format, but I would like to accept at least the same format that is displayed in the control, which I think is the most UI friendly, since there is always a default date displayed.