date-fns#sub TypeScript Examples

The following examples show how to use date-fns#sub. 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 gio-design with Apache License 2.0 7 votes vote down vote up
parseStartAndEndDate = (timeRange: string | undefined): [Date | undefined, Date | undefined] => {
  if (!timeRange || timeRange.split(':').length !== 2) {
    return [undefined, undefined];
  }
  const items = timeRange.split(':');
  const times = items[1].split(',').map((str) => parseInt(str, 10));
  const today = startOfToday();
  const yesterday = startOfYesterday();
  if (items[0] === 'since') {
    if (times.length === 1) {
      return [new Date(times[0]), today];
    }
    return [new Date(times[0]), sub(today, { days: times[1] })];
  }
  if (items[0] === 'since-lt-today') {
    if (times.length === 1) {
      return [new Date(times[0]), yesterday];
    }
    return [new Date(times[0]), sub(yesterday, { days: times[1] })];
  }
  if (items[0] === 'abs') {
    return [new Date(times[0]), new Date(times[1])];
  }
  if (items[0] === 'day') {
    return [sub(today, { days: times[0] - 1 }), sub(today, { days: times[1] })];
  }
  return [undefined, undefined];
}
Example #2
Source File: hooks.ts    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
useTokenPriceData = (
  address: string,
  interval: number,
  timeWindow: Duration,
): PriceChartEntry[] | undefined => {
  const dispatch = useDispatch<AppDispatch>()
  const token = useSelector((state: AppState) => state.info.tokens.byAddress[address])
  const priceData = token.priceData[interval]
  const [error, setError] = useState(false)

  // construct timestamps and check if we need to fetch more data
  const oldestTimestampFetched = token.priceData.oldestFetchedTimestamp
  const utcCurrentTime = getUnixTime(new Date()) * 1000
  const startTimestamp = getUnixTime(startOfHour(sub(utcCurrentTime, timeWindow)))

  useEffect(() => {
    const fetch = async () => {
      const { data, error: fetchingError } = await fetchTokenPriceData(address, interval, startTimestamp)
      if (data) {
        dispatch(
          updateTokenPriceData({
            tokenAddress: address,
            secondsInterval: interval,
            priceData: data,
            oldestFetchedTimestamp: startTimestamp,
          }),
        )
      }
      if (fetchingError) {
        setError(true)
      }
    }
    if (!priceData && !error) {
      fetch()
    }
  }, [address, dispatch, error, interval, oldestTimestampFetched, priceData, startTimestamp, timeWindow])

  return priceData
}
Example #3
Source File: updateLPsAPR.ts    From glide-frontend with GNU General Public License v3.0 5 votes vote down vote up
getWeekAgoTimestamp = () => {
  const weekAgo = sub(new Date(), { weeks: 1 })
  return getUnixTime(weekAgo)
}
Example #4
Source File: go.ts    From logseq-plugin-vim-shortcuts with MIT License 5 votes vote down vote up
parsePageName = async (pageName: string) => {
  const config = await logseq.App.getUserConfigs();
  const page = await logseq.Editor.getCurrentPage();
  switch (pageName) {
    case "@":
    case "@index":
      return "Contents";
    case "@today":
      pageName = format(new Date(), config.preferredDateFormat);
      return pageName;
    case "@yesterday":
      pageName = format(
        sub(new Date(), {
          days: 1,
        }),
        config.preferredDateFormat
      );
      return pageName;
    case "@tomorrow":
      pageName = format(
        add(new Date(), {
          days: 1,
        }),
        config.preferredDateFormat
      );
      return pageName;
    case "@prev":
      if (page && page["journal?"]) {
        pageName = format(
          sub(new Date(page.name), {
            days: 1,
          }),
          config.preferredDateFormat
        );
        return pageName;
      } else {
        pageName = format(
          sub(new Date(), {
            days: 1,
          }),
          config.preferredDateFormat
        );
        return pageName;
      }
    case "@next":
      if (page && page["journal?"]) {
        pageName = format(
          add(new Date(page.name), {
            days: 1,
          }),
          config.preferredDateFormat
        );
        return pageName;
      } else {
        pageName = format(
          add(new Date(), {
            days: 1,
          }),
          config.preferredDateFormat
        );
        return pageName;
      }
    case "@back":
      await backward();
      return;
    case "@forward":
      await forward();
      return;
    default:
      return pageName;
  }
}
Example #5
Source File: updateLPsAPR.ts    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
getWeekAgoTimestamp = () => {
  const weekAgo = sub(new Date(), { weeks: 1 })
  return getUnixTime(weekAgo)
}
Example #6
Source File: DayStrip.tsx    From nyxo-app with GNU General Public License v3.0 4 votes vote down vote up
CalendarStrip: FC = () => {
  const { selectDate, selectedDate } = useCalendar()
  const flatListRef = useRef<FlatList>(null)
  const [init, setInit] = useState(true)
  const dispatch = useAppDispatch()
  const startDate = new Date()

  const days = Array.from(Array(365 * 3)).map((_, index) =>
    startOfDay(sub(startDate, { days: index }))
  )

  const toggleCalendar = () => {
    dispatch(toggleCalendarModal(true))
  }

  const renderItem: ListRenderItem<Date> = ({ item, index }) => (
    <PressableContainer key={item.toISOString()} onPress={toggleCalendar}>
      <Day isFirst={index === 0}>
        <DateContainer isFirst={index === 0}>
          {localizedFormat(item, 'EEE d. LLL')}
        </DateContainer>
      </Day>
    </PressableContainer>
  )

  const handleViewableItemsChanged = ({
    viewableItems
  }: {
    viewableItems: Array<ViewToken>
  }) => {
    if (viewableItems.length === 1) {
      const date = viewableItems[0].item
      selectDate(date)
    }
  }

  const handleViewableItemsChangedRef = useRef(handleViewableItemsChanged)

  const viewabilityConfig = {
    itemVisiblePercentThreshold: 85,
    minimumViewTime: 750
  }

  const keyExtractor = (item: Date) => item.toISOString()

  const scrollToItem = (index: number) => {
    return flatListRef?.current?.scrollToIndex({
      index,
      animated: true,
      viewPosition: 0.5
    })
  }

  useEffect(() => {
    if (!init) {
      const index = days.findIndex((date) =>
        isSameDay(date, new Date(selectedDate))
      )
      if (index >= 0) {
        scrollToItem(index)
      }
    } else {
      setInit(false)
    }
  }, [days, init, selectedDate])

  const getItemLayout = (_: unknown, index: number) => {
    if (index === 0) {
      return {
        index,
        length: FIRST_DAY_WIDTH,
        offset: 0
      }
    }
    return {
      index,
      length: DAY_WIDTH,
      offset: FIRST_DAY_WIDTH + DAY_WIDTH * index - DAY_WIDTH
    }
  }

  const snapOffsets = days.map((_, index) => {
    if (index === 0) {
      return DAY_WIDTH
    }
    return DAY_WIDTH * (index + 1)
  })

  return (
    <Container>
      <FlatList
        ref={flatListRef}
        showsHorizontalScrollIndicator={false}
        inverted
        snapToStart
        horizontal
        getItemLayout={getItemLayout}
        keyExtractor={keyExtractor}
        viewabilityConfig={viewabilityConfig}
        onViewableItemsChanged={handleViewableItemsChangedRef.current}
        decelerationRate="fast"
        snapToOffsets={snapOffsets}
        data={days}
        renderItem={renderItem}
      />
      <Gradient pointerEvents="box-none" />
    </Container>
  )
}
Example #7
Source File: main.test.ts    From purge-artifacts-action with MIT License 4 votes vote down vote up
describe('shouldDelete', () => {
  test('expired', () => {
    const days = 2
    const expireInMs = days * 86400000
    const expiredArtifact = { created_at: sub(new Date(), { days }) }
    const actionInptus: IActionInputs = {
      expireInMs,
      onlyPrefix: '',
      exceptPrefix: ''
    }
    expect(shouldDelete(expiredArtifact as any, actionInptus)).toEqual(true)
  })
  test('not expired', () => {
    const days = 2
    const expireInMs = (days + 1) * 86400000
    const expiredArtifact = { created_at: sub(new Date(), { days }) }
    const actionInptus: IActionInputs = {
      expireInMs,
      onlyPrefix: '',
      exceptPrefix: ''
    }
    expect(shouldDelete(expiredArtifact as any, actionInptus)).toEqual(false)
  })
  test('expired when expireInDays is zero', () => {
    const expiredArtifact = { created_at: new Date() }
    const actionInptus: IActionInputs = {
      expireInMs: 0,
      onlyPrefix: '',
      exceptPrefix: ''
    }
    expect(shouldDelete(expiredArtifact as any, actionInptus)).toEqual(true)
  })
  test('should delete when matched by onlyPrefix', () => {
    const expiredArtifact = {
      created_at: new Date(),
      name: 'tmp_artifact.test'
    }
    const actionInptus: IActionInputs = {
      expireInMs: 0,
      onlyPrefix: 'tmp',
      exceptPrefix: ''
    }
    expect(shouldDelete(expiredArtifact as any, actionInptus)).toEqual(true)
  })
  test('should not delete when not matched by onlyPrefix', () => {
    const expiredArtifact = {
      created_at: new Date(),
      name: 'build_artifact.test'
    }
    const actionInptus: IActionInputs = {
      expireInMs: 0,
      onlyPrefix: 'tmp',
      exceptPrefix: ''
    }
    expect(shouldDelete(expiredArtifact as any, actionInptus)).toEqual(false)
  })
  test('should delete when not matched by exceptPrefix', () => {
    const expiredArtifact = {
      created_at: new Date(),
      name: 'tmp_artifact.test'
    }
    const actionInptus: IActionInputs = {
      expireInMs: 0,
      onlyPrefix: '',
      exceptPrefix: 'master_'
    }
    expect(shouldDelete(expiredArtifact as any, actionInptus)).toEqual(true)
  })
  test('should not delete when matched by exceptPrefix', () => {
    const expiredArtifact = {
      created_at: new Date(),
      name: 'master_artifact.test'
    }
    const actionInptus: IActionInputs = {
      expireInMs: 0,
      onlyPrefix: '',
      exceptPrefix: 'master_'
    }
    expect(shouldDelete(expiredArtifact as any, actionInptus)).toEqual(false)
  })
  test('should not delete when matched by both onlyPrefix and exceptPrefix', () => {
    const expiredArtifact = {
      created_at: new Date(),
      name: 'master_tmp_artifact.test'
    }
    const actionInptus: IActionInputs = {
      expireInMs: 0,
      onlyPrefix: 'master_',
      exceptPrefix: 'master_tmp_'
    }
    expect(shouldDelete(expiredArtifact as any, actionInptus)).toEqual(false)
  })
  test('should delete when matched by onlyPrefix but not exceptPrefix', () => {
    const expiredArtifact = {
      created_at: new Date(),
      name: 'master_tmp_artifact.test'
    }
    const actionInptus: IActionInputs = {
      expireInMs: 0,
      onlyPrefix: 'master_',
      exceptPrefix: 'tmp_'
    }
    expect(shouldDelete(expiredArtifact as any, actionInptus)).toEqual(true)
  })
})