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

Dayjs本地化问题:设置en-gb locale后日期解析为何异常?

为什么设置en-gb本地化后,dayjs仍按美国格式解析日期?

你遇到的问题核心在于:dayjs的locale设置仅控制日期的输出格式和本地化文本(如月份、星期的英文名称),并不会改变它默认的日期字符串解析规则。

当你直接传入'01/02/2000'这种无格式声明的字符串时,dayjs会默认采用美式的MM/DD/YYYY规则去解析,所以才会把原本的2月1日识别成1月2日。

解决方法

要让dayjs按照en-gb的DD/MM/YYYY格式解析日期,必须使用customParseFormat插件明确指定解析格式,步骤如下:

  1. 导入customParseFormat插件并启用
  2. 解析日期时,通过第二个参数指定格式DD/MM/YYYY

修正后的代码示例:

import dayjs from 'dayjs'
import 'dayjs/locale/en-gb'
import customParseFormat from 'dayjs/plugin/customParseFormat'

// 启用插件
dayjs.extend(customParseFormat)
// 设置本地化
dayjs.locale('en-gb')

const date = '01/02/2000' // 1st Feb
console.log(dayjs(date, 'DD/MM/YYYY').format('DD/MM/YYYY')) // 01/02/2000 (正确!)

这样就能确保dayjs按照你期望的DD/MM/YYYY格式解析输入的日期字符串了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:34:53