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

dayjs计算UTC时间差时小时数异常问题求助

Dayjs计算UTC时间差时小时数错误的问题

问题详情

在Node.js + TypeScript环境中使用dayjs计算两个UTC时间的差值,代码如下:

import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import utc from 'dayjs/plugin/utc'
...
dayjs.extend(duration)
dayjs.extend(utc)
...
const date1 = dayjs().utc() // 2024-10-31T06:58:42Z
const date2 = dayjs('2025-03-13 00:00:00').utc()
const diff = dayjs.duration(date2.diff(date1))

返回结果里的小时数明显不符合预期:

diff {
  '$d': {
    years: 0,
    months: 4,
    days: 11,
    hours: 0, // 此处错误!
    minutes: 1,
    seconds: 17,
    milliseconds: 5
  },
  '$l': 'en',
  '$ms': 11462477005
}

使用版本:dayjs 1.11.12;Node.js 23.0.0

补充信息:该问题存在于dayjs 1.11.9及以上版本,已提交相关Issue。

问题原因

这是dayjs 1.11.9版本后引入的框架bug,并非你的代码操作有错误。

临时解决方案

  • 降级dayjs版本:将dayjs降级至1.11.8,该版本可正常计算UTC时间差的小时数。
  • 手动推导小时数:利用duration的总毫秒数或asHours()方法计算正确的小时数,示例:
// 方式1:快速获取剩余小时数
const days = diff.days();
const correctHours = Math.floor(diff.asHours() - days * 24);

// 方式2:完整拆分所有时间单位
const totalMs = diff.asMilliseconds();
const years = Math.floor(totalMs / (1000 * 60 * 60 * 24 * 365));
const remainingMsAfterYears = totalMs % (1000 * 60 * 60 * 24 * 365);
const months = Math.floor(remainingMsAfterYears / (1000 * 60 * 60 * 24 * 30.4375));
const remainingMsAfterMonths = remainingMsAfterYears % (1000 * 60 * 60 * 24 * 30.4375);
const days = Math.floor(remainingMsAfterMonths / (1000 * 60 * 60 * 24));
const remainingMsAfterDays = remainingMsAfterMonths % (1000 * 60 * 60 * 24);
const hours = Math.floor(remainingMsAfterDays / (1000 * 60 * 60));
// 分钟、秒、毫秒可按相同逻辑推导
  • 使用原生Date API替代:如果不需要dayjs的其他特性,可直接用原生API计算:
const date1 = new Date('2024-10-31T06:58:42Z');
const date2 = new Date('2025-03-13T00:00:00Z');
const diffMs = date2.getTime() - date1.getTime();

const hours = Math.floor(diffMs / (1000 * 60 * 60)) % 24;
const days = Math.floor(diffMs / (1000 * 60 * 60 * 24));
// 其他时间单位可按此逻辑推导

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 19:03:13