Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

date parsing doesn't guard against unsupported locales #26

Open
philwhiteuk opened this issue Mar 7, 2023 · 1 comment
Open

date parsing doesn't guard against unsupported locales #26

philwhiteuk opened this issue Mar 7, 2023 · 1 comment

Comments

@philwhiteuk
Copy link
Contributor

The dateTimeFormat function depends on the requested locale being supported by the host system which isn't always the case.

export function dateTimeFormat(locale: string, options: Options) {
return new Intl.DateTimeFormat(locale, {...options, timeZone: 'UTC'});
}

By default Intl.DateTimeFormat uses a "best fit" algorithm to match the requested locale and so if the locale is not known it returns the default:

... The runtime compares it against the locales it has available and picks the best one available...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation

e.g.

new Intl.DateTimeFormat('foo', { day: 'numeric', month: 'numeric', year: 'numeric', timeZone: 'UTC'}).format(Date.now())
// outputs something like '07/03/2023'

Ideally, when parsing a date, I would like a way to guard against the locale being unsupported without having to do this outside of the totallylazy library. Intl does support this through the use of Intl.DateTimeFormat.supportedLocalesOf.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/supportedLocalesOf

e.g.

Intl.DateTimeFormat.supportedLocalesOf('en') // ['en']
Intl.DateTimeFormat.supportedLocalesOf('foo') // []
@aballal
Copy link
Contributor

aballal commented Mar 7, 2023

Maybe this is the expectation?

it('does not interchange the day and month when the locale is not supported', function () {
    // in an environment where locale "de" is not supported
    const option: Options = { day: 'numeric', month: 'numeric', year: 'numeric' };
    expect(Intl.DateTimeFormat.supportedLocalesOf('de')).to.eql([]);
    expect(parser('de', option).parse('03.06.2023')).to.not.eql(new Date('2023-03-06'));
    expect(parser('de', option).parse('03.06.2023')).to.eql(undefined);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants