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

使用DayJS计算英国格式日期间隔及diff方法报错解决方案

错误原因

  • dayjs().format() 方法返回的是字符串类型,只有Day.js实例对象才拥有.diff()方法,因此提前调用format后再调用diff自然会抛出类型错误。
  • Day.js默认不支持直接解析DD/MM/YYYY格式的日期字符串,直接传入该格式文本会生成无效的Day.js实例,操作时就会报无效日期错误。

解决步骤

1. 引入日期自定义解析插件

要解析非标准格式的日期,需要先引入Day.js的customParseFormat插件:

// NPM引入方式
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.extend(customParseFormat)

// 如果是CDN引入,直接加载对应插件脚本即可

2. 正确代码示例

// 解析指定格式的日期字符串,第二个参数传入对应的日期格式
const date1 = dayjs('31/10/2021', 'DD/MM/YYYY')
// 计算间隔时保留Day.js实例,不要提前调用format转字符串
const date2 = dayjs()

// 计算间隔天数,diff默认向下取整,需要向上取整可加第三个参数true后自行处理
const diffDays = date2.diff(date1, 'days')

// 按需求输出对应结果
let output
if (diffDays === 0) {
  output = 'Today'
} else if (diffDays === 1) {
  output = 'Tomorrow'
} else {
  output = `${diffDays} days time`
}

// 需要展示格式化日期时单独调用format即可
const formattedDate1 = date1.format('DD/MM/YYYY')
const formattedDate2 = date2.format('DD/MM/YYYY')

注意事项

所有日期计算都必须基于Day.js实例完成,.format()仅在需要将日期转为字符串展示的阶段调用即可,不要将转换后的字符串参与日期计算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:24:03