luxon#Duration TypeScript Examples

The following examples show how to use luxon#Duration. 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: format-utils.ts    From Discord-Bot-TypeScript-Template with MIT License 7 votes vote down vote up
public static duration(milliseconds: number, langCode: LangCode): string {
        return Duration.fromObject(
            Object.fromEntries(
                Object.entries(
                    Duration.fromMillis(milliseconds, { locale: Language.locale(langCode) })
                        .shiftTo(
                            'year',
                            'quarter',
                            'month',
                            'week',
                            'day',
                            'hour',
                            'minute',
                            'second'
                        )
                        .toObject()
                ).filter(([_, value]) => !!value) // Remove units that are 0
            )
        ).toHuman({ maximumFractionDigits: 0 });
    }
Example #2
Source File: util.ts    From backstage with Apache License 2.0 7 votes vote down vote up
export function nowPlus(duration: Duration | undefined, knex: Knex) {
  const seconds = duration?.as('seconds') ?? 0;
  if (!seconds) {
    return knex.fn.now();
  }
  return knex.client.config.client.includes('sqlite3')
    ? knex.raw(`datetime('now', ?)`, [`${seconds} seconds`])
    : knex.raw(`now() + interval '${seconds} seconds'`);
}
Example #3
Source File: process-event.ts    From posthog-foss with MIT License 6 votes vote down vote up
public handleTimestamp(data: PluginEvent, now: DateTime, sentAt: DateTime | null): DateTime {
        if (data['timestamp']) {
            if (sentAt) {
                // sent_at - timestamp == now - x
                // x = now + (timestamp - sent_at)
                try {
                    // timestamp and sent_at must both be in the same format: either both with or both without timezones
                    // otherwise we can't get a diff to add to now
                    return now.plus(parseDate(data['timestamp']).diff(sentAt))
                } catch (error) {
                    status.error('⚠️', 'Error when handling timestamp:', error)
                    Sentry.captureException(error, { extra: { data, now, sentAt } })
                }
            }
            return parseDate(data['timestamp'])
        }
        if (data['offset']) {
            return now.minus(Duration.fromMillis(data['offset']))
        }
        return now
    }
Example #4
Source File: mock-api.ts    From backstage with Apache License 2.0 6 votes vote down vote up
mockData: CodeClimateData = {
  repoID: '6b8cc37a64b741dd9d516119',
  maintainability: {
    letter: maintainabilityData.letter,
    value: humanizeDuration(
      Duration.fromObject(maintainabilityValue).toMillis(),
      { largest: 1 },
    ),
  },
  testCoverage: {
    letter: testCoverageData.letter,
    value: testCoverageData.measure.value.toFixed(),
  },
  numberOfCodeSmells: 97,
  numberOfDuplication: 49,
  numberOfOtherIssues: 26,
}
Example #5
Source File: parse.ts    From obsidian-dataview with MIT License 6 votes vote down vote up
DURATION_TYPES = {
    year: Duration.fromObject({ years: 1 }),
    years: Duration.fromObject({ years: 1 }),
    yr: Duration.fromObject({ years: 1 }),
    yrs: Duration.fromObject({ years: 1 }),

    month: Duration.fromObject({ months: 1 }),
    months: Duration.fromObject({ months: 1 }),
    mo: Duration.fromObject({ months: 1 }),
    mos: Duration.fromObject({ months: 1 }),

    week: Duration.fromObject({ weeks: 1 }),
    weeks: Duration.fromObject({ weeks: 1 }),
    wk: Duration.fromObject({ weeks: 1 }),
    wks: Duration.fromObject({ weeks: 1 }),
    w: Duration.fromObject({ weeks: 1 }),

    day: Duration.fromObject({ days: 1 }),
    days: Duration.fromObject({ days: 1 }),
    d: Duration.fromObject({ days: 1 }),

    hour: Duration.fromObject({ hours: 1 }),
    hours: Duration.fromObject({ hours: 1 }),
    hr: Duration.fromObject({ hours: 1 }),
    hrs: Duration.fromObject({ hours: 1 }),
    h: Duration.fromObject({ hours: 1 }),

    minute: Duration.fromObject({ minutes: 1 }),
    minutes: Duration.fromObject({ minutes: 1 }),
    min: Duration.fromObject({ minutes: 1 }),
    mins: Duration.fromObject({ minutes: 1 }),
    m: Duration.fromObject({ minutes: 1 }),

    second: Duration.fromObject({ seconds: 1 }),
    seconds: Duration.fromObject({ seconds: 1 }),
    sec: Duration.fromObject({ seconds: 1 }),
    secs: Duration.fromObject({ seconds: 1 }),
    s: Duration.fromObject({ seconds: 1 }),
}
Example #6
Source File: StartupUtils.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
static shouldDisplayLapsedUserMsg(): boolean {
    const ONE_DAY = Duration.fromObject({ days: 1 });
    const ONE_WEEK = Duration.fromObject({ weeks: 1 });
    const CUR_TIME = Duration.fromObject({ seconds: Time.now().toSeconds() });
    const metaData = MetadataService.instance().getMeta();

    // If we haven't prompted the user yet and it's been a day since their
    // initial install OR if it's been one week since we last prompted the user

    const lapsedUserMsgSendTime = metaData.lapsedUserMsgSendTime;
    if (lapsedUserMsgSendTime !== undefined) {
      MetadataService.instance().setLapsedUserSurveyStatus(
        LapsedUserSurveyStatusEnum.cancelled
      );
    }

    const refreshMsg =
      (metaData.lapsedUserMsgSendTime === undefined &&
        ONE_DAY <=
          CUR_TIME.minus(
            Duration.fromObject({ seconds: metaData.firstInstall })
          )) ||
      (metaData.lapsedUserMsgSendTime !== undefined &&
        ONE_WEEK <=
          CUR_TIME.minus(
            Duration.fromObject({ seconds: metaData.lapsedUserMsgSendTime })
          ));

    // If the user has never initialized, has never activated a dendron workspace,
    // and it's time to refresh the lapsed user message
    return (
      !metaData.dendronWorkspaceActivated &&
      !metaData.firstWsInitialize &&
      refreshMsg
    );
  }
Example #7
Source File: index.tsx    From resume-nextjs with MIT License 6 votes vote down vote up
function getFormattingExperienceTotalDuration(payload: IExperience.Payload) {
  const durations = payload.list
    .map((item) => {
      return {
        endedAt: item.endedAt
          ? DateTime.fromFormat(item.endedAt, Util.LUXON_DATE_FORMAT.YYYY_LL)
          : DateTime.local(),
        startedAt: DateTime.fromFormat(item.startedAt, Util.LUXON_DATE_FORMAT.YYYY_LL),
      };
    })
    .map(({ endedAt, startedAt }) => {
      return endedAt.plus({ month: 1 }).diff(startedAt);
    });

  const totalExperience = durations.reduce((prev, cur) => prev.plus(cur), Duration.fromMillis(0));

  return totalExperience.toFormat(`총 ${Util.LUXON_DATE_FORMAT.DURATION_KINDNESS}`);
}
Example #8
Source File: utils.ts    From programmer-fa with MIT License 6 votes vote down vote up
getDiffBetweenDateTimeAndNowInDays = (date: DateTime): Duration => (
  DateTime.now().diff(date, 'days')
)
Example #9
Source File: LocalTaskWorker.ts    From backstage with Apache License 2.0 6 votes vote down vote up
private async sleep(
    duration: Duration,
    abortSignal?: AbortSignal,
  ): Promise<void> {
    this.abortWait = delegateAbortController(abortSignal);
    await sleep(duration, this.abortWait.signal);
    this.abortWait.abort(); // cleans up resources
    this.abortWait = undefined;
  }
Example #10
Source File: plugin-api.ts    From obsidian-dataview with MIT License 5 votes vote down vote up
/** Attempt to extract a duration from a string or duration. */
    public duration(str: string | Duration): Duration | null {
        return this.func.dur(str) as Duration | null;
    }
Example #11
Source File: TaskWorker.ts    From backstage with Apache License 2.0 5 votes vote down vote up
DEFAULT_WORK_CHECK_FREQUENCY = Duration.fromObject({ seconds: 5 })
Example #12
Source File: windowWatcher.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
private onDidChangeActiveTextEditor = sentryReportingCallback(
    async (editor: TextEditor | undefined) => {
      const ctx = "WindowWatcher:onDidChangeActiveTextEditor";
      if (
        !editor ||
        editor.document.uri.fsPath !==
          window.activeTextEditor?.document.uri.fsPath
      ) {
        return;
      }

      // check and prompt duplicate warning.
      DoctorUtils.findDuplicateNoteAndPromptIfNecessary(
        editor.document,
        "onDidChangeActiveTextEditor"
      );

      // TODO: changing this to `this._extension.wsUtils.` will fails some tests that
      // mock the extension. Change once that is fixed.
      const note = ExtensionProvider.getWSUtils().getNoteFromDocument(
        editor.document
      );
      if (_.isUndefined(note)) {
        return;
      }

      Logger.info({ ctx, editor: editor.document.uri.fsPath });

      this.triggerUpdateDecorations(editor);

      // If automatically show preview is enabled, then open the preview
      // whenever text editor changed, as long as it's not already opened:
      if (
        this._extension.workspaceService?.config.preview
          ?.automaticallyShowPreview
      ) {
        if (!this._preview.isOpen()) {
          await this._preview.show();
        }
      }

      // If the opened note is still the active text editor 5 seconds after
      // opening, then count it as a valid 'viewed' event
      setTimeout(() => {
        if (
          editor.document.uri.fsPath ===
          window.activeTextEditor?.document.uri.fsPath
        ) {
          const now = Time.now().toMillis();

          const daysSinceCreated = Math.round(
            Duration.fromMillis(now - note.created).as("days")
          );

          const daysSinceUpdated = Math.round(
            Duration.fromMillis(now - note.updated).as("days")
          );

          AnalyticsUtils.track(EngagementEvents.NoteViewed, {
            daysSinceCreation: daysSinceCreated,
            daysSinceUpdate: daysSinceUpdated,
          });
        }
      }, 5000);
    }
  );
Example #13
Source File: TechInsightsDatabase.test.ts    From backstage with Apache License 2.0 5 votes vote down vote up
farInTheFuture = DateTime.now()
  .plus(Duration.fromMillis(555666777))
  .toISO()
Example #14
Source File: inline-api.ts    From obsidian-dataview with MIT License 5 votes vote down vote up
/** Attempt to extract a duration from a string or duration. */
    public duration(dur: string | Duration): Duration | null {
        return this.api.duration(dur);
    }
Example #15
Source File: ServerTokenManager.ts    From backstage with Apache License 2.0 5 votes vote down vote up
TOKEN_REISSUE_AFTER = Duration.fromObject({ minutes: 10 })
Example #16
Source File: transferable.test.ts    From obsidian-dataview with MIT License 5 votes vote down vote up
test("Duration", () => expect(roundTrip(Duration.fromMillis(10000)).toMillis()).toEqual(10000));
Example #17
Source File: Cards.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
WidgetContent = ({
  loading,
  latestRun,
}: {
  loading?: boolean;
  latestRun?: Project;
  branch: string;
}) => {
  const classes = useStyles();
  if (loading || !latestRun) return <LinearProgress />;
  const displayDate = DateTime.fromMillis(
    latestRun.lastBuild.timestamp,
  ).toRelative();
  const displayDuration =
    (latestRun.lastBuild.building ? 'Running for ' : '') +
    DateTime.local()
      .minus(Duration.fromMillis(latestRun.lastBuild.duration))
      .toRelative({ locale: 'en' })
      ?.replace(' ago', '');

  return (
    <StructuredMetadataTable
      metadata={{
        status: (
          <>
            <JenkinsRunStatus status={latestRun.lastBuild.status} />
          </>
        ),
        build: latestRun.fullDisplayName,
        'latest run': displayDate,
        duration: displayDuration,
        link: (
          <Link to={latestRun.lastBuild.url}>
            See more on Jenkins{' '}
            <ExternalLinkIcon className={classes.externalLinkIcon} />
          </Link>
        ),
      }}
    />
  );
}
Example #18
Source File: StartupUtils.ts    From dendron with GNU Affero General Public License v3.0 4 votes vote down vote up
static shouldDisplayInactiveUserSurvey(): boolean {
    const metaData = MetadataService.instance().getMeta();

    const inactiveSurveyMsgStatus = metaData.inactiveUserMsgStatus;
    if (inactiveSurveyMsgStatus === InactvieUserMsgStatusEnum.submitted) {
      return false;
    }

    // rare case where global state has been reset (or a reinstall) may cause issues with
    // the prompt logic. ignore these cases and don't show the
    if (
      metaData.firstInstall !== undefined &&
      metaData.firstLookupTime !== undefined
    ) {
      if (metaData.firstLookupTime - metaData.firstInstall < 0) {
        return false;
      }
    }

    const ONE_WEEK = Duration.fromObject({ weeks: 1 });
    const FOUR_WEEKS = Duration.fromObject({ weeks: 4 });
    const currentTime = Time.now().toSeconds();
    const CUR_TIME = Duration.fromObject({ seconds: currentTime });

    const FIRST_INSTALL =
      metaData.firstInstall !== undefined
        ? Duration.fromObject({ seconds: metaData.firstInstall })
        : undefined;

    const FIRST_LOOKUP_TIME =
      metaData.firstLookupTime !== undefined
        ? Duration.fromObject({ seconds: metaData.firstLookupTime })
        : undefined;

    const LAST_LOOKUP_TIME =
      metaData.lastLookupTime !== undefined
        ? Duration.fromObject({ seconds: metaData.lastLookupTime })
        : undefined;

    const INACTIVE_USER_MSG_SEND_TIME =
      metaData.inactiveUserMsgSendTime !== undefined
        ? Duration.fromObject({ seconds: metaData.inactiveUserMsgSendTime })
        : undefined;

    // is the user a first week active user?
    const isFirstWeekActive =
      FIRST_INSTALL !== undefined &&
      FIRST_LOOKUP_TIME !== undefined &&
      FIRST_LOOKUP_TIME.minus(FIRST_INSTALL) <= ONE_WEEK;

    // was the user active on the first week but has been inactive for more than four weeks?
    const isInactive =
      isFirstWeekActive &&
      LAST_LOOKUP_TIME !== undefined &&
      CUR_TIME.minus(LAST_LOOKUP_TIME) >= FOUR_WEEKS;

    // if they have cancelled last time, we should be waiting another four weeks.
    if (inactiveSurveyMsgStatus === InactvieUserMsgStatusEnum.cancelled) {
      const shouldSendAgain =
        INACTIVE_USER_MSG_SEND_TIME !== undefined &&
        CUR_TIME.minus(INACTIVE_USER_MSG_SEND_TIME) >= FOUR_WEEKS &&
        isInactive;
      if (shouldSendAgain) {
        AnalyticsUtils.track(SurveyEvents.InactiveUserSurveyPromptReason, {
          reason: "reprompt",
          currentTime,
          ...metaData,
        });
      }
      return shouldSendAgain;
    } else {
      // this is the first time we are asking them.
      const shouldSend =
        metaData.dendronWorkspaceActivated !== undefined &&
        metaData.firstWsInitialize !== undefined &&
        isInactive &&
        // this is needed since we may have prompted them before we introduced this metadata
        metaData.inactiveUserMsgSendTime === undefined;
      if (shouldSend) {
        AnalyticsUtils.track(SurveyEvents.InactiveUserSurveyPromptReason, {
          reason: "initial_prompt",
          currentTime,
          ...metaData,
        });
      }
      return shouldSend;
    }
  }
Example #19
Source File: IncidentListItem.tsx    From backstage with Apache License 2.0 4 votes vote down vote up
IncidentListItem = ({
  incident,
  readOnly,
  onIncidentAction,
  team,
}: Props) => {
  const classes = useStyles();
  const duration =
    new Date().getTime() - new Date(incident.startTime!).getTime();
  const createdAt = DateTime.local()
    .minus(Duration.fromMillis(duration))
    .toRelative({ locale: 'en' });
  const alertApi = useApi(alertApiRef);
  const api = useApi(splunkOnCallApiRef);

  const hasBeenManuallyTriggered = incident.monitorName?.includes('vouser-');

  const source = () => {
    if (hasBeenManuallyTriggered) {
      return incident.monitorName?.replace('vouser-', '');
    }
    if (incident.monitorType === 'API') {
      return '{ REST }';
    }

    return incident.monitorName;
  };

  const [{ value: resolveValue, error: resolveError }, handleResolveIncident] =
    useAsyncFn(
      async ({ incidentId, incidentType }: TriggerAlarmRequest) =>
        await api.incidentAction({
          routingKey: team,
          incidentType,
          incidentId,
        }),
    );

  const [
    { value: acknowledgeValue, error: acknowledgeError },
    handleAcknowledgeIncident,
  ] = useAsyncFn(
    async ({ incidentId, incidentType }: TriggerAlarmRequest) =>
      await api.incidentAction({
        routingKey: team,
        incidentType,
        incidentId,
      }),
  );

  useEffect(() => {
    if (acknowledgeValue) {
      alertApi.post({
        message: `Incident successfully acknowledged`,
      });
    }

    if (resolveValue) {
      alertApi.post({
        message: `Incident successfully resolved`,
      });
    }
    if (resolveValue || acknowledgeValue) {
      onIncidentAction();
    }
  }, [acknowledgeValue, resolveValue, alertApi, onIncidentAction]);

  if (acknowledgeError) {
    alertApi.post({
      message: `Failed to acknowledge incident. ${acknowledgeError.message}`,
      severity: 'error',
    });
  }

  if (resolveError) {
    alertApi.post({
      message: `Failed to resolve incident. ${resolveError.message}`,
      severity: 'error',
    });
  }

  return (
    <ListItem dense key={incident.entityId}>
      <ListItemIcon className={classes.listItemIcon}>
        <Tooltip
          title={incidentPhaseTooltip(incident.currentPhase)}
          placement="top"
        >
          <div className={classes.denseListIcon}>
            <IncidentPhaseStatus currentPhase={incident.currentPhase} />
          </div>
        </Tooltip>
      </ListItemIcon>
      <ListItemText
        primary={incident.entityDisplayName}
        primaryTypographyProps={{
          variant: 'body1',
          className: classes.listItemPrimary,
        }}
        secondary={
          <Typography noWrap variant="body2" color="textSecondary">
            #{incident.incidentNumber} - Created {createdAt}{' '}
            {source() && `by ${source()}`}
          </Typography>
        }
      />

      {incident.incidentLink && incident.incidentNumber && (
        <ListItemSecondaryAction>
          {!readOnly && (
            <IncidentAction
              currentPhase={incident.currentPhase || ''}
              incidentId={incident.entityId}
              resolveAction={handleResolveIncident}
              acknowledgeAction={handleAcknowledgeIncident}
            />
          )}
          <Tooltip title="View in Splunk On-Call" placement="top">
            <IconButton
              href={incident.incidentLink}
              target="_blank"
              rel="noopener noreferrer"
              color="primary"
            >
              <OpenInBrowserIcon />
            </IconButton>
          </Tooltip>
        </ListItemSecondaryAction>
      )}
    </ListItem>
  );
}