Format TimeBlocks

Format TimeBlocks

by Andrew Gerst

HTML

<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-1970-2030.min.js"></script>
<pre id="content"></pre>

JavaScript

// Moment JS - Formatting Guide: http://momentjs.com/docs/#/parsing/string-format/

const customTimezone = ['America/Los_Angeles', 'US/Mountain', 'US/Central', 'US/Eastern', 'America/Chicago', 'America/New_York', 'Europe/London', 'UTC'][7];
const startTime = '2019-04-24T07:00:00.000Z';
const addPrettyDate = true;
const dateFormat = 'MM/DD/YYYY h:mm a - dddd';

const timeblocks = [
  {
    entryduration: 120,
    entrystartminutessunday: 4740,
    exitduration: 120,
    exitstartminutessunday: 4740,
    id: 1107056,
  },
];

document.getElementById('content').innerText = JSON.stringify(timeblocks.map(formatTimeBlock), null, 2);

function formatTimeBlock(timeBlockPassed) {
  const timeBlock = JSON.parse(JSON.stringify(timeBlockPassed));
  if (!timeBlock.exitstartminutessunday) {
    timeBlock.exitstartminutessunday = timeBlock.entrystartminutessunday;
  }
  if (!timeBlock.exitduration) {
    timeBlock.exitduration = timeBlock.entryduration;
  }
  const startOfWeek = moment(startTime).tz(customTimezone).clone().startOf('week');
  const formattedTimeBlock = {
    entry: {
      startTime: addToMoment(startOfWeek, timeBlock.entrystartminutessunday, 'minutes'),
      endTime: addToMoment(startOfWeek, timeBlock.entrystartminutessunday + timeBlock.entryduration, 'minutes'),
    },
    exit: {
      startTime: addToMoment(startOfWeek, timeBlock.exitstartminutessunday, 'minutes'),
      endTime: addToMoment(startOfWeek, timeBlock.exitstartminutessunday + timeBlock.exitduration, 'minutes'),
    },
  };
  if (formattedTimeBlock.exit.startTime.isBefore(formattedTimeBlock.entry.startTime)) {
    formattedTimeBlock.exit.startTime = addToMoment(formattedTimeBlock.exit.startTime, 1, 'weeks');
  }
  if (formattedTimeBlock.exit.endTime.isBefore(formattedTimeBlock.entry.endTime)) {
    formattedTimeBlock.exit.endTime = addToMoment(formattedTimeBlock.exit.endTime, 1, 'weeks');
  }
  if (addPrettyDate) {
    formattedTimeBlock.pretty = {};
    formattedTimeBlock.pretty.entry = {};
   ...