Skip to content

Commit 56f1e5c

Browse files
committed
fix: fall back to the default locale when formatting with an unknown locale
1 parent f427515 commit 56f1e5c

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

src/impl/locale.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,15 @@ class PolyDateFormatter {
263263

264264
const intlOpts = { ...this.opts };
265265
intlOpts.timeZone = intlOpts.timeZone || z;
266-
this.dtf = getCachedDTF(intl, intlOpts);
266+
267+
// Intl silently falls back to the system locale for unknown locales, so the
268+
// default locale is listed as a backup for Intl to prefer over the system one.
269+
// The formatter cache is keyed by the locales list, so changing
270+
// Settings.defaultLocale picks up new formatters.
271+
this.dtf =
272+
Settings.defaultLocale && Settings.defaultLocale !== intl
273+
? getCachedDTF([intl, Settings.defaultLocale], intlOpts)
274+
: getCachedDTF(intl, intlOpts);
267275
}
268276

269277
format() {

test/datetime/toFormat.test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
import { DateTime } from "../../src/luxon";
44

5+
const Helpers = require("../helpers");
6+
const { withDefaultLocale } = Helpers;
7+
58
const dt = DateTime.fromObject(
69
{
710
year: 1982,
@@ -28,6 +31,23 @@ test("DateTime#toFormat accepts the locale from the DateTime or the options", ()
2831
expect(dt.setLocale("pt").toFormat("LLLL", { locale: "fr" })).toBe("mai");
2932
});
3033

34+
test("DateTime#toFormat falls back to the default locale for unsupported locales", () => {
35+
withDefaultLocale("fr", () => {
36+
expect(dt.toFormat("LLLL", { locale: "zz" })).toBe("mai");
37+
expect(dt.toFormat("ffff", { locale: "zz" })).toBe(dt.toFormat("ffff", { locale: "fr" }));
38+
});
39+
});
40+
41+
test("DateTime#toFormat picks up changes of the default locale for unsupported locales", () => {
42+
withDefaultLocale("fr", () => {
43+
expect(dt.toFormat("LLLL", { locale: "zz" })).toBe("mai");
44+
});
45+
46+
withDefaultLocale("en-US", () => {
47+
expect(dt.toFormat("LLLL", { locale: "zz" })).toBe("May");
48+
});
49+
});
50+
3151
test("DateTime#toFormat('u') returns fractional seconds", () => {
3252
expect(dt.toFormat("u")).toBe("123");
3353
expect(dt.set({ millisecond: 82 }).toFormat("u")).toBe("082");

0 commit comments

Comments
 (0)