[英]Localize date-fns
I had a working solution for date-fns using the following:我使用以下方法为 date-fns 提供了一个有效的解决方案:
const formatMonth = format("MMM");
Then I imported the locale and tried the following:然后我导入了语言环境并尝试了以下操作:
import { de } from 'date-fns/locale';
const formatMonth = format("MMM", {locale: de});
Getting the error: RangeError: Invalid time value.得到错误:RangeError:无效的时间值。 How do I change the language to german?
如何将语言更改为德语? The docs kinda suggest exactly the same, but it's not working.
文档有点暗示完全相同,但它不起作用。
EDIT: Maybe that is relevant and showcases, why the new Date() is not necessary for the format:编辑:也许这是相关的并展示了为什么格式不需要 new Date() :
const months = eachMonthOfInterval({
start: startOfYear(value),
end: endOfYear(value)
});
{months.map((month) => (
<ListboxOption
key={month.toDateString()}
value={month}
date={formatMonth(month)}
disabled={!isOlderThen18Years(month)}
></ListboxOption>
))}
Also, this code works in code sandbox, but won't in my react application.此外,此代码在代码沙箱中有效,但在我的 React 应用程序中无效。 Still throwing an error: RangeError: Invalid time value.
仍然抛出错误:RangeError: Invalid time value。
import { format } from 'date-fns';
import { de } from 'date-fns/locale';
const date = new Date();
console.log( format(
date, 'MMM',
{ awareOfUnicodeTokens: true, locale: de}
) );
As you are using the FP version to format a date you need to use the formatWithOptions
function to pass the locale options.当您使用 FP 版本来格式化日期时,您需要使用
formatWithOptions
函数来传递区域设置选项。
import format from "date-fns/fp/formatWithOptions";
It has a slightly different function signature then the format
function, where you need to pass the options as the first argument.它的函数签名与
format
函数略有不同,您需要将选项作为第一个参数传递。
const formatMonth = format({ locale: de }, "MMM");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.