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

使用date-fns计算两个Epoch时间秒差得到-0,求解决方法

解决date-fns differenceInSeconds返回-0的问题

问题出在你传入的是秒级Epoch时间戳,但differenceInSeconds方法的参数需要是Date对象或者毫秒级时间戳(JavaScript的Date构造函数默认接收毫秒级时间戳)。

直接传秒级时间戳的话,内部会把它当作毫秒数处理,相当于两个时间的实际间隔是:1673252582 - 1673253317 = -735毫秒,也就是-0.735秒,differenceInSeconds取整后就会返回-0(JavaScript中存在-0这个特殊值,逻辑上和0等价,但显示上会带负号)。

正确处理方式

有两种可行的方法:

  • 将秒级时间戳转换为Date对象传入:
    import { differenceInSeconds } from 'date-fns';
    
    const timestamp1 = 1673252582;
    const timestamp2 = 1673253317;
    const diff = differenceInSeconds(new Date(timestamp1 * 1000), new Date(timestamp2 * 1000));
    // 结果为 -735
    
  • 直接将秒级时间戳乘以1000转为毫秒级传入:
    import { differenceInSeconds } from 'date-fns';
    
    const timestamp1 = 1673252582;
    const timestamp2 = 1673253317;
    const diff = differenceInSeconds(timestamp1 * 1000, timestamp2 * 1000);
    // 结果为 -735
    

另外需要注意:differenceInSeconds(dateLeft, dateRight)的返回值是dateLeft减去dateRight的秒数。如果想得到正数的时间差,可以调换参数顺序,或者用Math.abs()包裹结果:

const diff = Math.abs(differenceInSeconds(new Date(timestamp1 * 1000), new Date(timestamp2 * 1000)));
// 结果为 735

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:45:26