#3186·dayjs

对于无效的日期操作数, diff(..., 'year'|'month', true) 返回 0,而不是 NaN

作者: yfwmaniish创建于 2026年8月25日更新于 2026年8月25日

描述错误

src/utils.js中的monthDiff通过其最后的|| 0NaN默默地转换为0:

const monthDiff = (a, b) => {
  if (a.date() < b.date()) return -monthDiff(b, a)
  const wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month())
  const anchor = a.clone().add(wholeMonthDiff, C.M)
  const c = b - anchor < 0
  const anchor2 = a.clone().add(wholeMonthDiff + (c ? -1 : 1), C.M)
  return +(-(wholeMonthDiff + ((b - anchor) / (c ? (anchor - anchor2) :
    (anchor2 - anchor)))) || 0)
}

这用于.diff(other, 'year'|'month', true)。当差异的两侧都是无效日期时,中间的算术自然会产生NaN,但结尾的|| 0将其转换为看起来合理的0,而不是传播无效性 - 因此.diff()默默地报告"相隔 0 个月",而实际上这是一个毫无意义的比较。