date-fns#differenceInMilliseconds TypeScript Examples

The following examples show how to use date-fns#differenceInMilliseconds. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CountdownLabel.tsx    From UUI with MIT License 6 votes vote down vote up
CountdownLabel = UUIFunctionComponent({
  name: 'CountdownLabel',
  nodes: {
    Root: 'label',
  },
  propTypes: CountdownLabelPropTypes,
}, (props: CountdownLabelFeatureProps, { nodes }) => {
  const { Root } = nodes

  const finalProps = {
    frequency: props.frequency || 1000,
    format: props.format || 'hh:mm:ss',
    allowNegative: props.allowNegative || false,
  }

  const generateLabelText = useCallback(() => {
    const diff = differenceInMilliseconds(props.until, new Date())
    const duration = (!props.allowNegative && diff && diff < 0)
      ? new Date(0)
      : addMilliseconds(addHours(new Date(0), 16), diff)
    return format(duration, finalProps.format)
  }, [finalProps.format, props.allowNegative, props.until])

  const [text, setText] = useState(generateLabelText())
  useInterval(() => {
    setText(generateLabelText())
  }, finalProps.frequency)

  return (
    <Root>{text}</Root>
  )
})
Example #2
Source File: NftForm.hooks.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
useNftFormUtils = () => {
  const { convertDurationToBlocks } = useBlockTimeEstimation()
  const { chainState } = useJoystream()

  const getNumberOfBlocks = (startDate: AuctionDatePickerValue, endDate: AuctionDatePickerValue) => {
    const start = (startDate?.type === 'date' && startDate.date) || new Date()
    if (endDate?.type === 'date') {
      return convertDurationToBlocks(differenceInMilliseconds(endDate.date, start))
    }
    if (endDate?.type === 'duration') {
      return convertDurationToBlocks(daysToMilliseconds(endDate.durationDays))
    }
    if (!endDate) {
      return 0
    }
  }

  return { getNumberOfBlocks, chainState }
}
Example #3
Source File: Timer.tsx    From amplication with Apache License 2.0 6 votes vote down vote up
function Timer({ startTime, endTime, runTimer }: Props) {
  const initialTime = useMemo(() => {
    const endDate = endTime ? new Date(endTime) : new Date();
    return differenceInMilliseconds(endDate, new Date(startTime));
  }, [startTime, endTime]);

  const startImmediately = !endTime && runTimer;

  //use a unique key to force re-render of Timer when startTime or endTime change
  const timerKey =
    (startTime ? startTime.toString() : "") +
    (endTime ? endTime.toString() : "");

  return (
    <span className={`${CLASS_NAME}`}>
      {!startTime ? (
        EMPTY_TIMER
      ) : (
        <TimerComponent
          key={timerKey}
          initialTime={initialTime}
          startImmediately={startImmediately}
        >
          <TimerComponent.Hours
            formatValue={(value) => (value ? `${value}h ` : "")}
          />
          <TimerComponent.Minutes />m <TimerComponent.Seconds />s
        </TimerComponent>
      )}
    </span>
  );
}
Example #4
Source File: BootProvider.tsx    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
function useRefreshToken(
  accessToken: AccessToken,
  refresh: () => Promise<unknown>,
) {
  const [refreshTokenTimeout, setRefreshTokenTimeout] = useState<number>();

  useEffect(() => {
    if (accessToken) {
      if (refreshTokenTimeout) {
        clearTimeout(refreshTokenTimeout);
      }
      const expiresInMillis = differenceInMilliseconds(
        new Date(accessToken.expiresIn),
        new Date(),
      );
      // Refresh token before it expires
      setRefreshTokenTimeout(
        window.setTimeout(refresh, expiresInMillis - 1000 * 60 * 2),
      );
    }
  }, [accessToken, refresh]);
}
Example #5
Source File: hooks.ts    From roamjs-com with MIT License 6 votes vote down vote up
monitor = <T>(label: string, callback: (props: T) => void) => (
  props: T
): void => {
  monitorCache[label] = (monitorCache[label] || 0) + 1;
  const start = new Date();
  console.log(label, "start", monitorCache[label]);
  callback(props);
  console.log(label, "end", differenceInMilliseconds(new Date(), start));
}
Example #6
Source File: nights.ts    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
getNightsAsDays = createSelector(getNights, (nights) => {
  const days = eachDayOfInterval({
    start: subDays(new Date(), 30),
    end: new Date() // lastDate
  })

  return days.map((day) => ({
    date: day.toISOString(),
    inBedDuration: 0,
    asleepDuration: 0,
    night: nights
      .filter((night) => matchDayAndNight(night.startDate, day.toISOString()))
      .map((night) => {
        const startDifference = differenceInMilliseconds(
          new Date(night.startDate),
          startOfDay(new Date(day))
        )

        const newStartDate = addMilliseconds(
          startOfDay(new Date()),
          startDifference
        )

        const newEndDate = addMinutes(newStartDate, night.totalDuration)

        return {
          ...night,
          startDate: newStartDate.valueOf(),
          endDate: newEndDate.valueOf()
        }
      })
  }))
})
Example #7
Source File: SleepChart.tsx    From nyxo-website with MIT License 6 votes vote down vote up
getNightAsDays = (nights: Night[]) => {
  const firstDate = min([...nights.map((night) => new Date(night.startDate))])
  const lastDate = max([...nights.map((night) => new Date(night.endDate))])

  const days = eachDayOfInterval({
    start: subDays(new Date(), 30),
    end: new Date(), // lastDate
  })

  return days.map((day) => ({
    date: day.toISOString(),
    night: nights
      .filter((night) => matchDayAndNight(night.startDate, day.toISOString()))
      .map((night) => {
        const startDifference = differenceInMilliseconds(
          new Date(night.startDate),
          startOfDay(new Date(day))
        )

        const newStartDate = addMilliseconds(
          startOfDay(new Date()),
          startDifference
        )

        const newEndDate = addMinutes(newStartDate, night.totalDuration)

        return {
          ...night,
          startDate: newStartDate.valueOf(),
          endDate: newEndDate.valueOf(),
        }
      }),
  }))
}
Example #8
Source File: formatters.ts    From jupyterlab-execute-time with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
getTimeDiff = (end: Date, start: Date): string => {
  // Human format based on loosely on ideas from:
  // https://github.com/ipython-contrib/jupyter_contrib_nbextensions/blob/master/src/jupyter_contrib_nbextensions/nbextensions/execute_time/ExecuteTime.js#L194
  const MS_IN_SEC = 1000;
  const MS_IN_MIN = 60 * MS_IN_SEC;
  const MS_IN_HR = 60 * MS_IN_MIN;
  const MS_IN_DAY = 24 * MS_IN_HR;

  let ms = differenceInMilliseconds(end, start);
  if (ms < MS_IN_SEC) {
    return `${ms}ms`;
  }
  const days = Math.floor(ms / MS_IN_DAY);
  ms = ms % MS_IN_DAY;

  const hours = Math.floor(ms / MS_IN_HR);
  ms = ms % MS_IN_HR;

  const mins = Math.floor(ms / MS_IN_MIN);
  ms = ms % MS_IN_MIN;

  // We want to show this as fractional
  const secs = ms / MS_IN_SEC;

  let timeDiff = '';
  if (days) {
    timeDiff += `${days}d `;
  }
  if (days || hours) {
    timeDiff += `${hours}h `;
  }
  if (days || hours || mins) {
    timeDiff += `${mins}m `;
  }
  // Only show s if its < 1 day
  if (!days) {
    // Only show ms if is < 1 hr
    timeDiff += `${secs.toFixed(hours ? 0 : 2)}s`;
  }
  return timeDiff.trim();
}
Example #9
Source File: ExecuteTimeWidget.ts    From jupyterlab-execute-time with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
   * Update the code cell to reflect the metadata
   * @param cell
   * @private
   */
  _updateCodeCell(cell: CodeCell, disableHighlight: boolean) {
    const executionMetadata = cell.model.metadata.get(
      'execution'
    ) as JSONObject;
    if (executionMetadata && JSONExt.isObject(executionMetadata)) {
      let executionTimeNode: HTMLDivElement = cell.node.querySelector(
        `.${EXECUTE_TIME_CLASS}`
      );
      const parentNode =
        this._settings.positioning === 'hover'
          ? cell.inputArea.node.parentNode
          : cell.inputArea.editorWidget.node;

      if (!executionTimeNode) {
        executionTimeNode = document.createElement('div') as HTMLDivElement;
        if (!cell.inputHidden) {
          parentNode.append(executionTimeNode);
        }
      } else if (executionTimeNode.parentNode !== parentNode) {
        executionTimeNode.remove();
        parentNode.append(executionTimeNode);
      }
      // Ensure that the current cell onclick actives the current cell
      executionTimeNode.onclick = () => {
        // This check makes sure that range selections (mostly) work
        // activate breaks the range selection otherwise
        if (this._tracker.activeCell !== cell) {
          cell.activate();
        }
      };

      let positioning;
      switch (this._settings.positioning) {
        case 'left':
          positioning = 'left';
          break;
        case 'right':
          positioning = 'right';
          break;
        case 'hover':
          positioning = 'hover';
          break;
        default:
          console.error(
            `'${positioning}' is not a valid type for the setting 'positioning'`
          );
      }
      const positioningClass = `${EXECUTE_TIME_CLASS}-positioning-${this._settings.positioning}`;
      const textContrastClass = `${EXECUTE_TIME_CLASS}-contrast-${this._settings.textContrast}`;
      executionTimeNode.className = `${EXECUTE_TIME_CLASS} ${positioningClass} ${textContrastClass}`;

      // More info about timing: https://jupyter-client.readthedocs.io/en/stable/messaging.html#messages-on-the-shell-router-dealer-channel
      // A cell is queued when the kernel has received the message
      // A cell is running when the kernel has started executing
      // A cell is done when the execute_reply has has finished
      const queuedTimeStr = executionMetadata['iopub.status.busy'] as
        | string
        | null;
      const queuedTime = queuedTimeStr ? new Date(queuedTimeStr) : null;
      const startTimeStr = (executionMetadata['shell.execute_reply.started'] ||
        executionMetadata['iopub.execute_input']) as string | null;
      // Using started is more accurate, but we don't get this until after the cell has finished executing
      const startTime = startTimeStr ? new Date(startTimeStr) : null;
      // This is the time the kernel is done processing and starts replying
      const endTimeStr = executionMetadata['shell.execute_reply'] as
        | string
        | null;
      const endTime = endTimeStr ? new Date(endTimeStr) : null;
      // shell.execute_reply can be one of:  One of: 'ok' OR 'error' OR 'aborted'
      // We want to remove the cases where it's not 'ok', but that's not in the metadata
      // So we assume that if iopub.execute_input never happened, the cell never ran, thus not ok.
      // This is assumed to be true because per the spec below, the code being executed should be sent to all frontends
      // See: https://jupyter-client.readthedocs.io/en/stable/messaging.html#messages-on-the-shell-router-dealer-channel
      // See: https://jupyter-client.readthedocs.io/en/stable/messaging.html#code-inputs
      const isLikelyAborted =
        endTimeStr && !executionMetadata['iopub.execute_input'];

      let msg = '';
      if (isLikelyAborted) {
        msg = '';
      } else if (endTime) {
        if (
          this._settings.minTime <=
          differenceInMilliseconds(endTime, startTime) / 1000.0
        ) {
          msg = `Last executed at ${getTimeString(endTime)} in ${getTimeDiff(
            endTime,
            startTime
          )}`;
        }
      } else if (startTime) {
        msg = `Execution started at ${getTimeString(startTime)}`;
      } else if (queuedTime) {
        msg = `Execution queued at ${getTimeString(queuedTime)}`;
      }
      if (executionTimeNode.innerText !== msg) {
        executionTimeNode.innerText = msg;
        if (!disableHighlight && this._settings.highlight && endTimeStr) {
          executionTimeNode.style.setProperty('animation', ANIMATE_CSS);
          setTimeout(
            () => executionTimeNode.style.removeProperty('animation'),
            ANIMATE_TIME_MS
          );
        }
      }
    } else {
      // Clean up in case it was removed
      this._removeExecuteNode(cell);
    }
  }
Example #10
Source File: serendipity.ts    From roamjs-com with MIT License 4 votes vote down vote up
runExtension(ID, () => {
  createConfigObserver({
    title: CONFIG,
    config: {
      tabs: [
        {
          id: "daily",
          fields: [
            {
              title: "includes",
              type: "pages",
              description:
                "Blocks and children tagged with one of these pages will be included for random selection.",
              defaultValue: ["books"],
            },
            {
              title: "excludes",
              type: "pages",
              description:
                "Blocks and children tagged with one of these pages will be excluded from random selection.",
            },
            {
              title: "timeout",
              type: "number",
              description:
                "Number of days that must pass for a block to be reconsidere for randoom selection",
              defaultValue: DEFAULT_TIMEOUT_COUNT,
            },
            {
              title: "label",
              type: "text",
              description:
                "The block text used that all chosen block refrences will be nested under.",
              defaultValue: DEFAULT_DAILY_LABEL,
            },
            {
              title: "count",
              type: "number",
              description: "The number of randomly chosen block references",
              defaultValue: DEFAULT_DAILY_COUNT,
            },
            {
              title: "character minimum",
              type: "number",
              description:
                "Blocks must have at least this many characters to be considered for random selection.",
            },
            {
              title: "word minimum",
              type: "number",
              description:
                "Block must have at least this many words to be considered for random selection.",
            },
            {
              title: "location",
              type: "select",
              description:
                "Where the daily serendipity block should be inserted on the DNP",
              options: {
                items: ["TOP", "BOTTOM"],
              },
            },
          ],
        },
      ],
    },
  });

  if (!localStorageGet(LOCAL_STORAGE_KEY)) {
    localStorageSet(LOCAL_STORAGE_KEY, JSON.stringify({ latest: 0 }));
  }

  const timeoutFunction = () => {
    const date = new Date();
    const todayPage = toRoamDate(date);
    const tree =
      getTreeByPageName("roam/js/serendipity").find((t) =>
        /daily/i.test(t.text)
      )?.children || [];
    const label = getSettingValueFromTree({
      tree,
      key: "label",
      defaultValue: DEFAULT_DAILY_LABEL,
    });
    const { latest } = JSON.parse(localStorageGet(LOCAL_STORAGE_KEY)) as {
      latest: number;
    };
    if (
      !getBlockUidByTextOnPage({ text: label, title: todayPage }) &&
      isAfter(startOfDay(date), startOfDay(latest))
    ) {
      pullDaily({ date, tree, label });
    }
    const tomorrow = addDays(startOfDay(date), 1);
    setTimeout(timeoutFunction, differenceInMilliseconds(tomorrow, date));
  };
  timeoutFunction();

  createButtonObserver({
    shortcut: "serendipity",
    attribute: "serendipity-daily",
    render: (b: HTMLButtonElement) => {
      const { blockUid } = getUidsFromButton(b);
      const todayPage = getPageTitleByBlockUid(blockUid);
      if (DAILY_NOTE_PAGE_REGEX.test(todayPage)) {
        b.onclick = () =>
          pullDaily({ date: parseRoamDate(todayPage) });
      } else {
        b.onclick = () => pullDaily({ date: new Date(), isDate: false });
      }
    },
  });

  window.roamAlphaAPI.ui.commandPalette.addCommand({
    label: 'Run Serendipity',
    callback: () => {
      const todayPage = getPageTitleByPageUid(getCurrentPageUid());
      if (DAILY_NOTE_PAGE_REGEX.test(todayPage)) {
        pullDaily({ date: parseRoamDate(todayPage) });
      } else {
        pullDaily({ date: new Date(), isDate: false });
      }
    }
  })

  createBlockObserver((b) => {
    const { blockUid, parentUid } = getUids(b);
    if (parentUid.length === 10) {
      const tree =
        getTreeByPageName("roam/js/serendipity").find((t) =>
          /daily/i.test(t.text)
        )?.children || [];
      const label = getSettingValueFromTree({
        tree,
        key: "label",
        defaultValue: DEFAULT_DAILY_LABEL,
      });
      const text = getTextByBlockUid(blockUid);
      if (text === label) {
        const container = b.closest(".rm-block-main");
        const icon = createIconButton("arrow-top-right");
        icon.style.position = "absolute";
        icon.style.top = "0";
        icon.style.right = "0";
        icon.addEventListener("click", () => {
          getTreeByBlockUid(blockUid).children.forEach((t) =>
            openBlockInSidebar(/\(\((.*?)\)\)/.exec(t.text)?.[1])
          );
        });
        container.append(icon);
      }
    }
  });
});