Skip to content

Commit

Permalink
locale fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
gerbenmeyer committed May 8, 2023
1 parent 70107a0 commit 93ca340
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
13 changes: 12 additions & 1 deletion __test__/API.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ describe('API', () => {

[localize, l].forEach((localizeFunction) => {
test('should return null when locale invalid', () => {
setLocale('nl-argh');
setLocale('argh');
const result = localizeFunction(1517774664107, { dateFormat: 'dates.long' });
expect(result).toEqual(null);
});
Expand Down Expand Up @@ -173,6 +173,17 @@ describe('API', () => {
const result = localizeFunction(dayjs.utc('2022-07-01T03:00:00.000Z').tz('America/Chihuahua'), { locale: 'nl', dateFormat: 'DD MMM YYYY, HH:mm Z' });
expect(result).toEqual('30 jun 2022, 21:00 -06:00');
});

test('should return date when locale can fall back', () => {
setLocale('nl-be');
const result = localizeFunction(1517774664107, { dateFormat: 'LL' });
expect(result).toEqual('4 februari 2018');
});

test('should return date when provided locale can fall back', () => {
const result = localizeFunction(1517774664107, { locale: 'zh-tw', dateFormat: 'LL' });
expect(result).toEqual('2018年2月4日');
});
});
});
});
2 changes: 1 addition & 1 deletion src/lib/localize.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default (value, options = {}) => {
if (locale === 'no') dayJsLocale = 'nb'; // Bokmål as default Norwegian

const parsedDate = (options.parseFormat ? dayjs(value, translate(options.parseFormat, {}, { locale, returnKeyOnError: true }), dayJsLocale) : dayjs(value)).locale(dayJsLocale);
if (parsedDate.locale() !== dayJsLocale) throw new Error('Invalid locale');
if (!dayJsLocale.startsWith(parsedDate.locale())) throw new Error('Invalid locale');

if (!parsedDate.isValid()) throw new Error('Invalid date');

Expand Down

0 comments on commit 93ca340

Please sign in to comment.