0

I'm working on a week calendar and to store appointments in DB I store them as scalar DateTime. The calendar that I'm working with only works with moment objects. I found that I can parse the DateTime as moment objects like this --> moment('2020-06-12T09:00:00.014Z'). I'm just wondering how I could efficiently reformat the appointmentToRender array so that start and end are no longer just DateTime's but moment object before passing the appointmentToRender array to <WeekCalendar />

appointmentToRender array structure:

appointmentToRender 
(2) [{…}, {…}]
0: {start: "2020-06-12T08:00:00.316Z", end: "2020-06-12T09:22:00.316Z", __typename: "Appointment"}
1: {start: "2020-06-14T09:00:00.390Z", end: "2020-06-14T10:22:00.390Z", __typename: "Appointment"}
length: 2
__proto__: Array(0)

1 Answer 1

1

You can simply set the properties as moment objects. Parse correctly as utc using: moment.utc() moment.utc('2020-06-12T09:22:00.316Z'); and simply set the properties.

You can then process using moment methods and properties.

Render calling the relevant format you need.

Simple demo:

// parse as UTC correctly 
const start = moment.utc('2020-06-12T09:22:00.316Z');
const end = start.clone().add(1, 'd');

const appointmentToRender = [{
  start: start,
  end: end,
  __typename: 'Appointment'
}];

const item = appointmentToRender[0];

// calcute using the moment objects
const diff = end.diff(start, 'h');
console.info(`${diff} hours difference`);

// format etc
console.info(item.end.format('ddd, Mo MMM YYYY, HH:mm'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment-with-locales.min.js"></script>

React:

import React, {useState} from "react";
import moment from 'moment';

export default function App() {
  const [data,] = useState(() => {
    // parse as UTC correctly 
    const start = moment.utc('2020-06-12T09:22:00.316Z');
    const end = start.clone().add(1, 'd');

    const appointmentToRender = [{
      start: start,
      end: end,
      __typename: 'Appointment'
    }];

    return appointmentToRender;
  });

  return (
    <div className="App">
      {data && data.map((item, index) => (
        <div key={index}>
          {item.end.format('ddd, Mo MMM YYYY, HH:mm')} ({item.end.diff(item.start, 'h')} hours long)
        </div>
      ))}
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.