Skip to content

Bug(release-4.22): incorrect duration calculation #16913

Description

@LiaoSirui

Code: https://github.com/openshift/console/blob/release-4.22/frontend/public/components/utils/build-utils.ts#L3-L33

export const displayDurationInWords = (start: string, stop: string): string => {
  if (!start) {
    return '-';
  }
  const startTime = new Date(start).getTime();
  const stopTime = stop ? new Date(stop).getTime() : new Date().getTime();
  let duration = Math.round((stopTime - startTime) / 1000);
  const time = [];
  let durationInWords = '';
  while (duration >= 60) {
    time.push(duration % 60);
    duration = Math.floor(duration / 60);
  }
  time.push(duration);
  if (time[2]) {
    durationInWords += `${time[2]} ${
      time[2] > 1 ? i18next.t('public~hours') : i18next.t('public~hour')
    } `;
  }
  if (time[1]) {
    durationInWords += `${time[1]} ${
      time[1] > 1 ? i18next.t('public~minutes') : i18next.t('public~minute')
    } `;
  }
  if (time[0]) {
    durationInWords += `${time[0]} ${
      time[0] > 1 ? i18next.t('public~seconds') : i18next.t('public~second')
    } `;
  }
  return durationInWords.trim();
};

Duration exceeding 60 hours causes an error

I'd suggest using the following calculation instead:

export const displayDurationInWords = (start: string, stop: string): string => {
  if (!start) {
    return '-';
  }
  const startTime = new Date(start).getTime();
  const stopTime = stop ? new Date(stop).getTime() : new Date().getTime();
  const duration = Math.max(0, Math.round((stopTime - startTime) / 1000));
  if (!Number.isFinite(duration)) {
    return '-';
  }
  const seconds = duration % 60;
  const minutes = Math.floor(duration / 60) % 60;
  const hours = Math.floor(duration / 3600) % 24;
  const days = Math.floor(duration / 86400);
  const durationInWords = [];
  if (days) {
    durationInWords.push(`${days} ${days > 1 ? i18next.t('public~days') : i18next.t('public~day')}`);
  }
  if (hours) {
    durationInWords.push(
      `${hours} ${hours > 1 ? i18next.t('public~hours') : i18next.t('public~hour')}`,
    );
  }
  if (minutes) {
    durationInWords.push(
      `${minutes} ${minutes > 1 ? i18next.t('public~minutes') : i18next.t('public~minute')}`,
    );
  }
  if (seconds || !durationInWords.length) {
    durationInWords.push(
      `${seconds} ${seconds === 1 ? i18next.t('public~second') : i18next.t('public~seconds')}`,
    );
  }
  return durationInWords.join(' ');
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions