moment#Duration TypeScript Examples

The following examples show how to use moment#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: utils.ts    From jitsu with MIT License 7 votes vote down vote up
/**
 *
 * @param event user event with Momet.js time at the top level
 * @param timeAgo Moment.Duration period of time from the current date after which the latest event is considered to be 'a long ago'
 * @returns {boolean} Whether the event was before the (currentDate - timeAgo)
 */
export function userEventWasTimeAgo(event: TimeFormattedUserEvent, timeAgo: Duration): boolean {
  return event.time.isBefore(moment().subtract(timeAgo))
}
Example #2
Source File: SidebarInfoCard.tsx    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
SidebarInfoCard = () => {
  const { guild_id: guildId } =
    useParams<{ chain_name?: string; guild_id?: string }>();
  const { data } = useGuildConfig(guildId);

  const quorum = useVotingPowerPercent(
    data?.votingPowerForProposalExecution,
    data?.totalLocked
  );

  return (
    <SidebarCard header={<SidebarCardHeader>Information</SidebarCardHeader>}>
      <SidebarCardContent>
        <Row>
          <Label>Consensus System</Label>
          <ColoredLabel>Guild</ColoredLabel>
        </Row>
        <Row>
          <Label>Proposal Duration</Label>
          <ColoredLabel>
            {data?.proposalTime ? (
              duration(data?.proposalTime?.toNumber(), 'seconds').humanize()
            ) : (
              <Skeleton width={50} />
            )}
          </ColoredLabel>
        </Row>
        <Row>
          <Label>Quorum</Label>
          <ColoredLabel>
            {quorum != null ? `${quorum}%` : <Skeleton width={50} />}
          </ColoredLabel>
        </Row>
      </SidebarCardContent>
    </SidebarCard>
  );
}
Example #3
Source File: MeetingPage.tsx    From msteams-meetings-template with MIT License 6 votes vote down vote up
function formatDuration(duration: Duration) {
  let str = '';
  if (Math.floor(duration.asDays()) > 0) {
    str += translate('meetingPage.duration.days', { days: Math.floor(duration.asDays()) });
  }
  if (duration.hours() > 0) {
    str += translate('meetingPage.duration.hours', { hours: duration.hours() });
  }
  if (duration.minutes() > 0) {
    str += translate('meetingPage.duration.minutes', { minutes: duration.minutes() });
  }
  return str;
}
Example #4
Source File: rendering.ts    From obsidian-tracker with MIT License 5 votes vote down vote up
function getXTickValues(
    dates: Moment[],
    interval: Duration
): [Array<Date>, d3.TimeInterval] {
    // The input interval could be null,
    // generate tick values even if interval is null

    // console.log(interval);

    let tickValues: Array<Date> = [];
    let tickInterval = null;

    // y values are time values
    if (interval) {
        let firstDate = dates[0];
        let lastDate = dates[dates.length - 1];
        tickValues = d3.timeDay.range(
            firstDate.toDate(),
            lastDate.toDate(),
            interval.asDays()
        );
    } else {
        let days = dates.length;
        if (days <= 15) {
            // number of ticks: 0-15
            tickInterval = d3.timeDay;
        } else if (days <= 4 * 15) {
            // number of ticks: 4-15
            tickInterval = d3.timeDay.every(4);
        } else if (days <= 7 * 15) {
            // number of ticks: 8-15
            tickInterval = d3.timeWeek;
        } else if (days <= 15 * 30) {
            // number of ticks: 4-15
            tickInterval = d3.timeMonth;
        } else if (days <= 15 * 60) {
            // number of ticks: 8-15
            tickInterval = d3.timeMonth.every(2);
        } else {
            tickInterval = d3.timeYear;
        }
    }

    return [tickValues, tickInterval];
}
Example #5
Source File: rendering.ts    From obsidian-tracker with MIT License 5 votes vote down vote up
function getYTickValues(
    yLower: number,
    yUpper: number,
    interval: number | Duration,
    isTimeValue = false
) {
    // The input interval could be null,
    // generate tick values for time values even if interval is null

    // console.log(interval);
    // console.log(isTimeValue);

    const absExtent = Math.abs(yUpper - yLower);
    let tickValues: Array<number> = [];

    if (!isTimeValue) {
        // y values are numbers
        if (interval && typeof interval === "number") {
            // !==null && !== 0
            tickValues = d3.range(yLower, yUpper, interval);
        }
    } else {
        // y values are time values
        if (interval && window.moment.isDuration(interval)) {
            let intervalInSeconds = Math.abs(interval.asSeconds());
            tickValues = d3.range(yLower, yUpper, intervalInSeconds);
        } else {
            // auto interval for time values
            if (absExtent > 5 * 60 * 60) {
                // extent over than 5 hours
                // tick on the hour
                yLower = Math.floor(yLower / 3600) * 3600;
                yUpper = Math.ceil(yUpper / 3600) * 3600;

                tickValues = d3.range(yLower, yUpper, 3600);
            } else {
                // tick on the half hour
                yLower = Math.floor(yLower / 1800) * 1800;
                yUpper = Math.ceil(yUpper / 1800) * 1800;

                tickValues = d3.range(yLower, yUpper, 1800);
            }
        }
    }

    if (tickValues.length === 0) return null;
    return tickValues;
}
Example #6
Source File: index.tsx    From dxvote with GNU Affero General Public License v3.0 4 votes vote down vote up
ProposalInfoCard: React.FC = () => {
  const [isHistoryExpanded, setIsHistoryExpanded] = useState(false);
  const { guild_id: guildId, proposal_id: proposalId } = useParams<{
    chain_name: string;
    guild_id?: string;
    proposal_id?: string;
  }>();
  const { data: proposal, error } = useProposal(guildId, proposalId);

  const { data: guildConfig } = useGuildConfig(guildId);
  const quorum = useVotingPowerPercent(
    guildConfig?.votingPowerForProposalExecution,
    guildConfig?.totalLocked
  );

  const endDetail = useMemo(() => {
    if (!proposal || !proposal.endTime) return null;

    const currentTime = moment();
    if (proposal.endTime.isBefore(currentTime)) {
      return `Ended ${proposal.endTime.fromNow()}`;
    } else {
      return `Ends ${proposal.endTime.toNow()}`;
    }
  }, [proposal]);

  if (error) return <div>Error</div>;

  return (
    <SidebarCard header={<SidebarCardHeader>Information</SidebarCardHeader>}>
      <SidebarCardContentUnpadded>
        <SidebarInfoContent>
          <InfoDetail>
            <span>Consensus System</span>
            <InfoDetailMuted>Guild</InfoDetailMuted>
          </InfoDetail>
          <InfoDetail>
            <span>Proposal Duration</span>
            <InfoDetailMuted>
              {guildConfig?.proposalTime ? (
                duration(
                  guildConfig?.proposalTime?.toNumber(),
                  'seconds'
                ).humanize()
              ) : (
                <Loading loading text skeletonProps={{ width: '50px' }} />
              )}
            </InfoDetailMuted>
          </InfoDetail>
          <InfoDetail>
            <span>Quorum</span>
            <InfoDetailMuted>
              {quorum != null ? (
                `${quorum}%`
              ) : (
                <Loading loading text skeletonProps={{ width: '50px' }} />
              )}
            </InfoDetailMuted>
          </InfoDetail>

          <InfoDetail>
            <span>Proposal History</span>
            <ProposalHistoryIcon
              active={isHistoryExpanded}
              onClick={() => setIsHistoryExpanded(!isHistoryExpanded)}
            >
              {isHistoryExpanded ? (
                <FiChevronUp height={16} />
              ) : (
                <FiChevronDown height={16} />
              )}
            </ProposalHistoryIcon>
          </InfoDetail>
        </SidebarInfoContent>

        {isHistoryExpanded && (
          <>
            <Separator />

            <SidebarInfoContent>
              {!proposal ? (
                <Loading loading text skeletonProps={{ height: '100px' }} />
              ) : (
                <>
                  <InfoItem
                    title="Proposal created"
                    description={proposal.startTime.format(
                      'MMM Do, YYYY - h:mm a'
                    )}
                  />
                  <InfoItem
                    title={endDetail}
                    description={proposal.endTime.format(
                      'MMM Do, YYYY - h:mm a'
                    )}
                  />
                </>
              )}
            </SidebarInfoContent>
          </>
        )}
      </SidebarCardContentUnpadded>
    </SidebarCard>
  );
}
Example #7
Source File: helper.ts    From obsidian-tracker with MIT License 4 votes vote down vote up
export function parseDurationString(strDuration: string) {
    //duration string format:
    //year (years, y, Y),
    //month (months, M), // m will conflict with minute!!!
    //week (weeks, w, W),
    //day (days, d, D),
    //hour (hours, h, H),
    //minute (minutes, m), // M will conflict with month!!!
    //second (seconds, s, S)
    if (!strDuration) return null;

    let duration: Duration = window.moment.duration(0);
    let hasValue = false;

    let negativeValue = false;
    if (strDuration.startsWith("+")) {
        negativeValue = false;
        strDuration = strDuration.substring(1);
    }
    if (strDuration.startsWith("-")) {
        negativeValue = true;
        strDuration = strDuration.substring(1);
    }

    let yearValue = null;
    [yearValue, strDuration] = extractValueFromDurationString(strDuration, [
        "year",
        "years",
        "Y",
        "y",
    ]);
    if (yearValue !== null) {
        if (negativeValue) {
            yearValue *= -1;
        }
        duration.add(yearValue, "years");
        hasValue = true;
    }

    let monthValue = null;
    [monthValue, strDuration] = extractValueFromDurationString(strDuration, [
        "month",
        "months",
        "M",
    ]);
    if (monthValue !== null) {
        if (negativeValue) {
            monthValue *= -1;
        }
        duration.add(monthValue, "months");
        hasValue = true;
    }

    let weekValue = null;
    [weekValue, strDuration] = extractValueFromDurationString(strDuration, [
        "week",
        "weeks",
        "W",
        "w",
    ]);
    if (weekValue !== null) {
        if (negativeValue) {
            weekValue *= -1;
        }
        duration.add(weekValue, "weeks");
        hasValue = true;
    }

    let dayValue = null;
    [dayValue, strDuration] = extractValueFromDurationString(strDuration, [
        "day",
        "days",
        "D",
        "d",
    ]);
    if (dayValue !== null) {
        if (negativeValue) {
            dayValue *= -1;
        }
        duration.add(dayValue, "days");
        hasValue = true;
    }

    let hourValue = null;
    [hourValue, strDuration] = extractValueFromDurationString(strDuration, [
        "hour",
        "hours",
        "H",
        "h",
    ]);
    if (hourValue !== null) {
        if (negativeValue) {
            hourValue *= -1;
        }
        duration.add(hourValue, "hours");
        hasValue = true;
    }

    let minuteValue = null;
    [minuteValue, strDuration] = extractValueFromDurationString(strDuration, [
        "minute",
        "minutes",
        "m",
    ]);
    if (minuteValue !== null) {
        if (negativeValue) {
            minuteValue *= -1;
        }
        duration.add(minuteValue, "minutes");
        hasValue = true;
    }

    let secondValue = null;
    [secondValue, strDuration] = extractValueFromDurationString(strDuration, [
        "second",
        "seconds",
        "S",
        "s",
    ]);
    if (secondValue !== null) {
        if (negativeValue) {
            secondValue *= -1;
        }
        duration.add(secondValue, "seconds");
        hasValue = true;
    }

    if (!hasValue) return null;
    return duration;
}