0

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"
 ..
}

Ideally I would like to save

duration: String!

in my GraphQL mutation, when creating an Event.

Could someone advise me how could this be done?

My stack:

  • React
  • Apollo
  • GraphQL

I have the following installed:
..

  • MomentJS
  • React Moment

..

Many thanks in advance

Scott Agirs
  • 599
  • 6
  • 14

2 Answers2

1

Having start(startsAt) and end(endsAt) dates you can easily calculate the duration on the Front-end side, somewhere in your React components.

Something like that:

// Convert `startsAt` and `endsAt` strings to moment date objects
const start = moment(state.Event.startsAt)
const end = moment(state.Event.endsAt)

// Calculate the duration
// Keep in mind you can get the duration in seconds, days, etc.
const duration = moment.duration(end.diff(start))
const hours = duration.asHours()
Jordan Enev
  • 16,904
  • 3
  • 42
  • 67
0

@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.

With Unix Timestamp this is how I achieved my goal:

Add plugins npm install moment-duration-format and import it:

..
import momentDurationFormatSetup from "moment-duration-format";


..

momentDurationFormatSetup(moment);
  const durationSeconds = (endsAt - startsAt) / 1000;
  const duration = moment.duration(durationSeconds, "seconds").format("mm");

..

also above I wrapped moment in a HOC momentDurationFormatString(), provided by the newly imported plugin

-then with React Moment render it:

..
import Moment from "react-moment";

..

<Moment unix format="dddd, Mo MMM, H:mm">
          {startsAt / 1000}
</Moment>
..
Scott Agirs
  • 599
  • 6
  • 14
  • The error is thrown because of [this](https://stackoverflow.com/questions/41093266/diff-is-not-a-function-in-moment-js). However, I'm happy that you resolve it on your own. – Jordan Enev Aug 23 '18 at 07:16