feat: allow setting calendar for i18n date formatting (#6430)

* feat: allow setting calendar for i18n date formatting

* fix TS

* add test
This commit is contained in:
Joshua Chen 2022-04-08 22:34:34 +08:00 committed by GitHub
parent 3e110054d7
commit 7941a46be3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 54 additions and 12 deletions

View file

@ -19,7 +19,11 @@ const DefaultI18N: I18n = {
currentLocale: 'en',
locales: ['en'],
defaultLocale: 'en',
localeConfigs: {},
localeConfigs: {
en: {
calendar: 'gregory',
},
},
};
function getBlogContentPaths(siteDir: string): BlogContentPaths {

View file

@ -41,7 +41,7 @@ function getI18n(locale: string): I18n {
currentLocale: locale,
locales: [locale],
defaultLocale: locale,
localeConfigs: {},
localeConfigs: {[locale]: {calendar: 'gregory'}},
};
}

View file

@ -151,13 +151,18 @@ export function parseBlogFileName(
return {date: undefined, text, slug};
}
function formatBlogPostDate(locale: string, date: Date): string {
function formatBlogPostDate(
locale: string,
date: Date,
calendar: string,
): string {
try {
return new Intl.DateTimeFormat(locale, {
day: 'numeric',
month: 'long',
year: 'numeric',
timeZone: 'UTC',
calendar,
}).format(date);
} catch (err) {
logger.error`Can't format blog post date "${String(date)}"`;
@ -253,7 +258,11 @@ async function processBlogSourceFile(
}
const date = await getDate();
const formattedDate = formatBlogPostDate(i18n.currentLocale, date);
const formattedDate = formatBlogPostDate(
i18n.currentLocale,
date,
i18n.localeConfigs[i18n.currentLocale]!.calendar,
);
const title = frontMatter.title ?? contentTitle ?? parsedBlogFileName.text;
const description = frontMatter.description ?? excerpt ?? '';