问题描述
我一直在尝试计算事件持续时间的最佳方法.
I've been trying to figure what's the best way to calculate duration of an event.
我有一个具有以下字段的收藏集:
I have a Collection with the following fields:
type Event {
..
startsAt: "HH:mm MM-DD-YYYY"
endsAt: "HH:mm MM-DD-YYYY"
..
}
理想情况下,我想保存
duration: String!
在创建事件时出现在我的GraphQL突变中.
in my GraphQL mutation, when creating an Event.
有人可以告诉我该怎么做吗?
Could someone advise me how could this be done?
我的堆栈:
- 反应
- 阿波罗
- GraphQL
我已安装以下设备:
..
I have the following installed:
..
- MomentJS
- 反应片刻
..
非常感谢
推荐答案
@Jordan Enev-非常感谢您的快速回复!出于某种原因,尝试此操作后将引发错误".diff"不是函数,我假设我必须另外导入一些内容.同样,我最终做出了一个重大决定,决定改用Unix时间戳.
@Jordan Enev - thanks a lot for quick response! For some reason after trying this it threw an error ".diff" is not a function, I'm assuming I had to import something additionally. Also I ended up making a radical decision to switch to Unix timestamps.
使用Unix时间戳,这就是我实现目标的方式:
With Unix Timestamp this is how I achieved my goal:
添加插件npm install moment-duration-format
并将其导入:
..
import momentDurationFormatSetup from "moment-duration-format";
..
momentDurationFormatSetup(moment);
const durationSeconds = (endsAt - startsAt) / 1000;
const duration = moment.duration(durationSeconds, "seconds").format("mm");
..
我还是在上面包裹了新导入的插件提供的HOC momentDurationFormatString()
also above I wrapped moment in a HOC momentDurationFormatString()
, provided by the newly imported plugin
-然后使用React Moment渲染它:
-then with React Moment render it:
..
import Moment from "react-moment";
..
<Moment unix format="dddd, Mo MMM, H:mm">
{startsAt / 1000}
</Moment>
..
这篇关于React MomentJS从开始时间和结束时间获取持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!