date-fns#differenceInHours TypeScript Examples

The following examples show how to use date-fns#differenceInHours. 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: experiments.ts    From abacus with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an experiment's run time in hours.
 */
export function getExperimentRunHours(experiment: ExperimentFull): number {
  if (experiment.status === Status.Staging) {
    return 0
  }

  const maybeEndDate = experiment.status === Status.Running ? new Date() : experiment.endDatetime
  return differenceInHours(maybeEndDate, experiment.startDatetime)
}
Example #2
Source File: helpers.tsx    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
processAuctionData = async (auctionId: number, auctionResponse: AuctionsResponse): Promise<Auction> => {
  const processedAuctionData = {
    ...auctionResponse,
    topLeaderboard: auctionResponse.leaderboard.toNumber(),
    initialBidAmount: ethersToBigNumber(auctionResponse.initialBidAmount).div(DEFAULT_TOKEN_DECIMAL).toNumber(),
    leaderboardThreshold: ethersToBigNumber(auctionResponse.leaderboardThreshold),
    startBlock: auctionResponse.startBlock.toNumber(),
    endBlock: auctionResponse.endBlock.toNumber(),
  }

  // Get all required data and blocks
  const currentBlock = await simpleRpcProvider.getBlockNumber()
  const startDate = await getDateForBlock(currentBlock, processedAuctionData.startBlock)
  const endDate = await getDateForBlock(currentBlock, processedAuctionData.endBlock)

  const auctionStatus = getAuctionStatus(
    currentBlock,
    processedAuctionData.startBlock,
    processedAuctionData.endBlock,
    processedAuctionData.status,
  )

  return {
    id: auctionId,
    startDate,
    endDate,
    auctionDuration: differenceInHours(endDate, startDate),
    ...processedAuctionData,
    status: auctionStatus,
  }
}
Example #3
Source File: analyses.test.ts    From abacus with GNU General Public License v2.0 5 votes vote down vote up
describe('getExperimentHealthIndicators', () => {
  it('should work correctly', () => {
    expect(
      Analyses.getExperimentHealthIndicators(
        Fixtures.createExperimentFull({
          variations: [
            { variationId: 1, allocatedPercentage: 50, isDefault: true, name: 'variation_name_1' },
            { variationId: 2, allocatedPercentage: 50, isDefault: false, name: 'variation_name_2' },
          ],
        }),
      ),
    ).toMatchInlineSnapshot(`
      Array [
        Object {
          "indication": Object {
            "code": "very low",
            "reason": "−∞ < x ≤ 3",
            "recommendation": "Experiments should generally run for at least a week before drawing conclusions.",
            "severity": "Warning",
          },
          "link": "https://github.com/Automattic/experimentation-platform/wiki/Experiment-Health#experiment-run-time",
          "name": "Experiment run time",
          "unit": "days",
          "value": 0,
        },
      ]
    `)
  })

  it('should work for an experiment that ran too long', () => {
    const experimentRunTimeDays = 50
    const startDatetime = subDays(new Date(), experimentRunTimeDays)
    const expectedExperimentRunTimeDays = differenceInHours(new Date(), startDatetime) / 24

    expect(
      Analyses.getExperimentHealthIndicators(
        Fixtures.createExperimentFull({
          startDatetime,
          status: Status.Running,
          variations: [
            { variationId: 1, allocatedPercentage: 50, isDefault: true, name: 'variation_name_1' },
            { variationId: 2, allocatedPercentage: 50, isDefault: false, name: 'variation_name_2' },
          ],
        }),
      ),
    ).toMatchInlineSnapshot(`
      Array [
        Object {
          "indication": Object {
            "code": "very high",
            "reason": "42 < x ≤ ∞",
            "recommendation": "Experiment has been running for way too long. Stopping it now is highly recommended.",
            "severity": "Warning",
          },
          "link": "https://github.com/Automattic/experimentation-platform/wiki/Experiment-Health#experiment-run-time",
          "name": "Experiment run time",
          "unit": "days",
          "value": ${expectedExperimentRunTimeDays},
        },
      ]
    `)
  })
})
Example #4
Source File: helpers.tsx    From glide-frontend with GNU General Public License v3.0 5 votes vote down vote up
processAuctionData = async (auctionId: number, auctionResponse: AuctionsResponse): Promise<Auction> => {
  const processedAuctionData = {
    ...auctionResponse,
    topLeaderboard: auctionResponse.leaderboard.toNumber(),
    initialBidAmount: ethersToBigNumber(auctionResponse.initialBidAmount).div(DEFAULT_TOKEN_DECIMAL).toNumber(),
    leaderboardThreshold: ethersToBigNumber(auctionResponse.leaderboardThreshold),
    startBlock: auctionResponse.startBlock.toNumber(),
    endBlock: auctionResponse.endBlock.toNumber(),
  }

  // Get all required datas and blocks
  const currentBlock = await simpleRpcProvider.getBlockNumber()
  const startDate = await getDateForBlock(currentBlock, processedAuctionData.startBlock)
  const endDate = await getDateForBlock(currentBlock, processedAuctionData.endBlock)
  const farmStartDate = add(endDate, { hours: 12 })
  const blocksToFarmStartDate = hoursToSeconds(12) / ESC_BLOCK_TIME
  const farmStartBlock = processedAuctionData.endBlock + blocksToFarmStartDate
  const farmDurationInBlocks = hoursToSeconds(7 * 24) / ESC_BLOCK_TIME
  const farmEndBlock = farmStartBlock + farmDurationInBlocks
  const farmEndDate = add(farmStartDate, { weeks: 1 })

  const auctionStatus = getAuctionStatus(
    currentBlock,
    processedAuctionData.startBlock,
    processedAuctionData.endBlock,
    processedAuctionData.status,
  )

  return {
    id: auctionId,
    startDate,
    endDate,
    auctionDuration: differenceInHours(endDate, startDate),
    farmStartBlock,
    farmStartDate,
    farmEndBlock,
    farmEndDate,
    ...processedAuctionData,
    status: auctionStatus,
  }
}
Example #5
Source File: useGetNftSlot.tsx    From atlas with GNU General Public License v3.0 4 votes vote down vote up
useGetNftSlot = ({
  englishTimerState,
  timerLoading,
  auctionPlannedEndDate,
  hasBuyNowPrice,
  needsSettling,
  startsAtDate,
  withNftLabel,
  status,
}: UseGetSlotsOpts): SlotsObject['bottomLeft'] => {
  const msTimestamp = useMsTimestamp({
    shouldStop: timerLoading || englishTimerState === 'expired' || !englishTimerState,
  })

  const generatePills: () => PillProps[] = useCallback(() => {
    const buyNowPill: PillProps = { icon: <SvgActionBuyNow />, variant: 'overlay', title: 'Buy now' }
    switch (status) {
      case 'idle':
        return [{ icon: <SvgActionNotForSale />, variant: 'overlay', title: 'Not for sale' }]
      case 'buy-now':
        return [buyNowPill]
      case 'auction': {
        const additionalBuyNowPill = hasBuyNowPrice ? [buyNowPill] : []
        if (needsSettling) {
          return [
            {
              icon: <SvgActionAuction />,
              label: 'To be settled',
              variant: 'overlay',
            },
            ...additionalBuyNowPill,
          ]
        }
        if (timerLoading) {
          return [
            {
              icon: <SvgActionAuction />,
              label: 'Loading',
              variant: 'overlay',
            },
            ...additionalBuyNowPill,
          ]
        }
        switch (englishTimerState) {
          case 'upcoming': {
            const diff = startsAtDate && differenceInSeconds(new Date(), startsAtDate) * -1
            const diffTime =
              diff && diff < 3600
                ? `Starts in ${formatDurationShort(diff)}`
                : startsAtDate && ` ${format(startsAtDate, 'd MMM')} at ${format(startsAtDate, 'HH:mm')}`
            return [
              {
                icon: <SvgActionClock />,
                label: diffTime,
                variant: 'overlay',
              },
              ...additionalBuyNowPill,
            ]
          }
          case 'running': {
            const diff = auctionPlannedEndDate && differenceInSeconds(auctionPlannedEndDate, new Date())
            const lessThanMinute = auctionPlannedEndDate && differenceInSeconds(auctionPlannedEndDate, msTimestamp) < 60
            const lessThanHour = auctionPlannedEndDate && differenceInHours(auctionPlannedEndDate, msTimestamp) < 1
            return [
              {
                icon: <SvgActionAuction />,
                label: diff ? (lessThanMinute ? '< 1 min' : formatDurationShort(diff, true)) : undefined,
                variant: lessThanHour ? 'danger' : 'overlay',
              },
              ...additionalBuyNowPill,
            ]
          }
          case 'expired':
            return [
              {
                icon: <SvgActionAuction />,
                label: 'Auction ended',
                variant: 'overlay',
              },
              ...additionalBuyNowPill,
            ]
          default:
            return []
        }
      }
      default:
        return []
    }
  }, [
    status,
    hasBuyNowPrice,
    needsSettling,
    timerLoading,
    englishTimerState,
    startsAtDate,
    auctionPlannedEndDate,
    msTimestamp,
  ])

  const nftPill: PillProps[] = withNftLabel ? [{ label: 'NFT', variant: 'overlay', title: 'NFT' }] : []

  return {
    element: <PillGroup items={[...nftPill, ...generatePills()]} />,
  }
}