javascript 我想做矩减法或差异

标签 javascript reactjs frontend

我想减去 event.startDatenextEvent.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"
    }
}

我尝试使用 diff 进行减法并尝试了 console.log,但输出了一个奇怪的值 1970-01-02 21:01:00

如果将两个值相减,则年份应为 2023 - 2023 = 0000,但查询结果为 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 (
    
  )
}

最佳答案

moment.diff() 给出两个日期之间的差异(以毫秒为单位)。代码片段如下:

const startTime = moment(hello.data?.event?.startDate);
const nextStartTime = moment(hello.data?.nextEvent?.startDate);
    
const duration = nextStartTime.diff(startTime)

为您提供以毫秒为单位的时间差,但现在将其转换为 moment 对象,您告诉它相当于“1970 年 1 月 1 日之后的duration 毫秒数”(此日期是大多数计算机用作“时间零”的默认值)。

如果您想获得时间上的个体差异,则必须单独指定:

// The false here specifies whether or not you want an integer (false)
// or a floating point number (true)
const durationYears = nextStartTime.diff(startTime, "years", false) 
const durationMonths = nextStartTime.diff(startTime, "months", false) % 12
const durationDays = nextStartTime.diff(startTime, "days", false) % 365
const durationHours = nextStartTime.diff(startTime, "hours", false)
const durationMinutes = nextStartTime.diff(startTime, "minutes", false) % 60
const durationSeconds = nextStartTime.diff(startTime, "seconds", false) % 60

通过在最后使用这些模数,您可以强制它保持在分配的时间以下。例如,63 分钟 mod 60 就是 3,这就是我们在显示数字时想要保留的内容。对于任何时间,请考虑它转入什么内容,以及在什么标记处(即,在 60 时将秒转入分钟,在 12 时将月转入年等)。通过对每个数字运行模运算符,我们保证它将小于该数字。

关于javascript 我想做矩减法或差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75141210/

相关文章:

java - 如何检查客户端网络/防火墙的端口是否打开?

reactjs - 当 linkWithPopup 出现错误时,如何获取凭证?

routes - 有没有办法保存 astro 的状态

javascript - ExtJS 4 : rendering a custom view from a grouped store with a title for the grouping

javascript - 使用正则表达式逐步验证时间戳

javascript - AngularJS Controller 未执行

reactjs - 尽管 Safari 桌面中的 overrideNative,VideoJS 没有质量级别/无法选择质量

javascript - React Material UI + 路由器重定向按钮

html - 响应式弹出窗口 CSS

javascript - 如何在没有任何副作用的情况下更新 package-lock.json 中的单个依赖项?