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

使用dayjs/date-fns解析dd/MM/yyyy格式日期遇异常求助

解决Dayjs/date-fns替换Momentjs时的日期解析异常问题

Dayjs 解决方案

Dayjs 默认没有内置自定义格式解析能力,直接用dayjs(dateStr, format)会失效,必须引入CustomParseFormat插件,同时开启严格解析模式才能确保只匹配指定格式:

修改后的代码示例:

<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<!-- 引入自定义解析插件 -->
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/customParseFormat.js"></script>
<script type="text/javascript">
    // 启用插件
    dayjs.extend(dayjs_plugin_customParseFormat);
    
    // 开启严格模式(第三个参数设为true)
    let a = dayjs('23/09/2022', 'DD/MM/YYYY', true).format('YYYY-MM-DD');
    console.log('date :' + a); // 输出 2022-09-23
    
    let b = dayjs('09/23/2022', 'DD/MM/YYYY', true).format('YYYY-MM-DD');
    console.log('date :' + b); // 输出 Invalid Date
</script>
</head>
</html>
  • 不引入插件的话,Dayjs会用原生new Date()解析字符串,导致09/23/2022被当成MM/DD/YYYY解析成功,不符合预期。
  • 严格模式开启后,只有完全匹配指定格式的字符串才会被解析,否则返回Invalid Date。

date-fns 解决方案

你使用的date-fns 1.x版本默认是宽松解析模式,需要在parse函数的第四个参数里开启严格模式:

修改后的代码示例:

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>
<script type="text/javascript">
    // 开启严格模式(第四个参数设为 { strict: true })
    let a = dateFns.parse('23/09/2022', 'dd/MM/yyyy', new Date(), { strict: true });
    console.log('date a:' + dateFns.format(a, "YYYY-MM-DD")); // 输出 2022-09-23
    
    let b = dateFns.parse('09/23/2022', 'dd/MM/yyyy', new Date(), { strict: true });
    console.log('date b:' + dateFns.format(b, "YYYY-MM-DD")); // 输出 Invalid Date
</script>
</head>
</html>

如果升级到date-fns 2.x,API略有调整,但严格模式参数依然适用,且新版本兼容性更好,推荐使用。

总结

  • Dayjs需依赖插件+严格模式实现精准解析,和Momentjs的默认行为有差异,无法直接无脑替换。
  • date-fns 1.x默认宽松解析,必须手动开启严格模式才能达到预期的格式校验效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:50:22