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

使用Moment.js计算日期差值出现1970基准时间异常求助

问题:计算两个日期时间差时出现1970年异常值的解决方法

问题场景

我需要计算event.startDate与nextEvent.startDate之间的时间差,数据如下(hello.json):

{
    "event": {
        "id": 932,
        "title": "123",
        "startDate": "2023-01-17T00:40:00.000Z",
        "endDate": "2023-01-17T03:29:46.000Z"
    },
    "nextEvent": {
        "id": 930,
        "title": "minsuhi",
        "startDate": "2023-01-18T13:20:00.000Z",
        "endDate": "2023-01-18T16:09:46.000Z"
    }
}

我尝试用moment的diff方法计算差值并打印,结果输出了异常值1970-01-02 21:01:00。按预期两个日期年份差应为0,但结果出现1970年,想知道diff的计算逻辑是不是理解错了,以及正确的计算方式是什么?

我的代码:

export default function View() {

    const startTime = moment(hello.data?.event?.startDate);
    const nextStartTime = moment(hello.data?.nextEvent?.startDate);
    
    const duration = nextStartTime.diff(startTime)
    const formattedDuration = moment(duration).format('YYYY-MM-DD HH:MM:SS')
    console.log(formattedDuration) // 1970-01-02 21:01:00

   return (
    
  )
}

问题原因

你对diff方法的理解有偏差:

  • nextStartTime.diff(startTime)返回的是两个时间点之间的毫秒数差值,不是一个日期对象。
  • 当你用moment(duration)包装这个毫秒数时,moment会把它当成Unix时间戳(即从1970-01-01T00:00:00.000Z开始经过的毫秒数),所以格式化后得到的是1970年的日期,这和你要的时间差完全不是一回事。

正确计算方式

要计算并格式化两个日期的时间差,应该用moment的duration对象来处理,而不是把毫秒数当成日期:

方法1:用moment.duration格式化时长

export default function View() {
    const startTime = moment(hello.data?.event?.startDate);
    const nextStartTime = moment(hello.data?.nextEvent?.startDate);
    
    // 创建duration对象表示时间差
    const duration = moment.duration(nextStartTime.diff(startTime));
    
    // 自定义格式化时长,比如年-月-日 时:分:秒
    const formattedDuration = `${duration.years()}年-${duration.months()}月-${duration.days()}日 ${duration.hours()}时:${duration.minutes()}分:${duration.seconds()}秒`;
    console.log(formattedDuration); // 输出:0年-0月-1日 12时:40分:0秒

    return (
    )
}

方法2:用diff指定单位获取各部分差值

如果只需要特定单位的差值,可以直接在diff方法里指定单位:

// 获取天数差
const dayDiff = nextStartTime.diff(startTime, 'days'); // 1
// 获取小时差
const hourDiff = nextStartTime.diff(startTime, 'hours'); // 36
// 获取分钟差
const minuteDiff = nextStartTime.diff(startTime, 'minutes'); // 2200

这样就能得到你预期的时间差结果,而不会出现1970年的异常日期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:45:36