You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

date-fns设置德语locale时报Invalid time value错误如何解决

问题根因

你之前的写法是date-fns FP(函数式编程)模块的柯里化用法,添加locale配置时用了默认非FP模块的参数顺序,导致参数传递错误,把格式字符串当成了日期参数解析,因此抛出RangeError: Invalid time value错误:

  • 默认导出的format函数参数顺序为:format(日期, 格式字符串, 配置项),不支持柯里化
  • FP模块导出的format函数参数顺序为:format(配置项, 格式字符串, 日期),支持柯里化,调用时只传前两个参数会返回接收日期的函数

解决方案

方案1:使用默认非柯里化版本(推荐,写法更直观)

直接在渲染时调用format,按默认参数顺序传参即可:

import { format, eachMonthOfInterval, startOfYear, endOfYear } from 'date-fns';
import { de } from 'date-fns/locale';

// 渲染逻辑
const months = eachMonthOfInterval({
    start: startOfYear(value),
    end: endOfYear(value)
});
{months.map((month) => (
   <ListboxOption
     key={month.toDateString()}
     value={month}
     date={format(month, 'MMM', { locale: de })}
     disabled={!isOlderThen18Years(month)}
   ></ListboxOption>
))}

方案2:保留柯里化用法,导入FP模块的format

如果要保持你之前提前封装formatMonth函数的写法,需要改为导入FP模块的format,按FP参数顺序传配置:

// 注意导入路径改为date-fns/fp
import { format } from 'date-fns/fp';
import { de } from 'date-fns/locale';

// 先传配置项,再传格式字符串,返回接收日期的函数
const formatMonth = format({ locale: de }, 'MMM');

// 后续调用方式和你之前一致
date={formatMonth(month)}

额外排查点

如果按上述写法调整后仍有报错,可按以下顺序排查:

  • 确认项目中安装的date-fns版本为v2/v3正式版,无版本冲突
  • 打印months数组中的每个month值,确认都是有效的Date对象,不存在Invalid Date或undefined的情况
  • 确认没有在文件中同时混用默认模块和FP模块的format导入,避免变量覆盖

内容的提问来源于stack exchange,提问作者Katharina Schreiber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 01:39:05