【发布时间】:2023-01-05 22:01:09
【问题描述】:
我有一个使用 Next.js 完成的多语言网站。 Next.js 提供了几种获取所有语言环境的方法,这里是:
{locale} // current locale in use 'es'
{locales} // all the configured locales in an array [ "en", "de", "es", "ja", "ru" ]
{defaultLocale} // if no locale provided, will use en
然后在我的代码中,我有这个 date-fns 方法来获取我从我的 createdAt 值获得的给定日期的天数距离。
// my import languages
import { es, de, ja, en, ru } from 'date-fns/locale';
<BodyOne>
This category was funded{' '}
{formatDistance(new Date(category.createdAt), new Date(), {
locale: locale,
})}
</BodyOne>
这给了我以下错误:
RangeError: locale must contain formatDistance property
我不明白为什么,这有效:
{
locale: es,
})}
但是这个具有可变区域设置的却没有。
{
locale: locale,
})}
如果我创建一个新常量,假设:
const myCurrentLang = es;
它有效,但如果我输出:
const myCurrentLang = 'es';
我收到错误:RangeError: locale must contain formatDistance property
也许我需要将“es”值转换为其他类型才能使 date-fns 工作。
【问题讨论】:
-
我已经阅读了文档date-fns.org/v2.28.0/docs/I18n 并创建了一个名为 whenHappened 的新实用程序库,它可以完美地打印日期格式。
Javascript // lib/dateFormat.js /** @format */ import { formatDistance } from 'date-fns'; import { es, de, ja, en, ru } from 'date-fns/locale'; const locales = { es, de, ja, en, ru }; export default function whenHappened(createdAt, localeId) { return formatDistance(new Date(), new Date(createdAt), { locale: locales[localeId], }); }
标签: javascript next.js date-fns