date-fns#isSameDay TypeScript Examples

The following examples show how to use date-fns#isSameDay. 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: priceHistoryProvider.ts    From akashlytics with GNU General Public License v3.0 6 votes vote down vote up
updatePriceHistory = async () => {
  try {
    isSyncingPrices = true;
    const endpointUrl = "https://api.coingecko.com/api/v3/coins/akash-network/market_chart?vs_currency=usd&days=max";

    console.log("Fetching latest market data from " + endpointUrl);

    const response = await fetch(endpointUrl);
    const data: PriceHistoryResponse = await response.json();
    const apiPrices = data.prices.map((pDate) => ({
      date: pDate[0],
      price: pDate[1]
    }));

    console.log(`There are ${apiPrices.length} prices to update.`);

    const days = await Day.findAll({
      where: {
        aktPrice: null
      }
    });

    for (const day of days) {
      const priceData = apiPrices.find((x) => isSameDay(new Date(x.date), day.date));

      if (priceData && priceData.price != day.aktPrice) {
        day.aktPrice = priceData.price;
        await day.save();
      }
    }
  } catch (err) {
    console.error(err);
    throw err;
  } finally {
    isSyncingPrices = false;
  }
}
Example #2
Source File: GraphUtils.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
static reduceBySum(
        splitList: GraphSplit[],
        splitSum: GraphSplit,
        useOriginalCurrency: boolean = false,
    ): GraphSplit[] {
        const amountField = useOriginalCurrency ? 'originalAmount' : 'amount';
        const currentSum: GraphSplit = _.clone(splitSum);
        const reducedList = [splitSum];
        for (const split of splitList) {
            const nextSum = currentSum[amountField] - split[amountField];
            split[amountField] = currentSum[amountField];
            currentSum[amountField] = nextSum;
            if (
                !isSameDay(
                    split.transactionDate,
                    reducedList[reducedList.length - 1].transactionDate,
                )
            ) {
                reducedList.push(split);
            }
        }

        return reducedList;
    }
Example #3
Source File: dateFormat.ts    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
export function postDateFormat(
  value: Date | number | string,
  now = new Date(),
): string {
  const date = new Date(value);

  // Calculate time delta in seconds.
  const dt = (now.getTime() - date.getTime()) / 1000;

  if (dt <= oneMinute) return 'Now';

  if (isSameDay(date, now)) {
    return 'Today';
  }

  if (isSameDay(date, subDays(now, 1))) return 'Yesterday';

  return date.toLocaleString('en-US', {
    month: 'short',
    day: '2-digit',
    year: 'numeric',
  });
}
Example #4
Source File: case_list.tsx    From j3pz-web with MIT License 6 votes vote down vote up
private getTime = (date: string) => {
        if (!date) return '';
        const now = new Date();
        const updateTime = new Date(date);
        if (isSameDay(now, updateTime)) {
            return format(updateTime, 'HH:mm');
        }
        if (isSameYear(now, updateTime)) {
            return format(updateTime, 'MM月dd日 HH:mm');
        }
        return format(updateTime, 'yyyy年MM月dd日 HH:mm');
    };
Example #5
Source File: WeeklyCalendar.tsx    From react-calendar with MIT License 6 votes vote down vote up
export function WeeklyBody<EventItem>({
  events,
  renderItem,
  style,
}: WeeklyBodyProps<EventItem>) {
  let { week, selectedDay } = useWeeklyCalendar();
  return (
    <div className="rc-overflow-auto rc-max-h-96" style={style}>
      <ul className="rc-divide-y rc-divide-gray-200 ">
        {events.map(item => {
          // If they select a single day, filter out events for different days
          if (selectedDay) {
            if (!isSameDay(selectedDay, item.date)) return null;
          }
          //if an event is for a different week, filter it out
          if (!isSameWeek(week, item.date)) return null;

          //return the remeaining events!
          return renderItem({
            item,
            showingFullWeek: selectedDay === undefined,
          });
        })}
      </ul>
    </div>
  );
}
Example #6
Source File: matchDayUtils.tsx    From symphony-ui-toolkit with Apache License 2.0 5 votes vote down vote up
function isDayAfter(day1: Date, day2: Date): boolean {
  return isAfter(day1, day2) && !isSameDay(day1, day2);
}
Example #7
Source File: matchDayUtils.tsx    From symphony-ui-toolkit with Apache License 2.0 5 votes vote down vote up
function isDayBefore(day1: Date, day2: Date): boolean {
  return isBefore(day1, day2) && !isSameDay(day1, day2);
}
Example #8
Source File: matchDayUtils.tsx    From symphony-ui-toolkit with Apache License 2.0 5 votes vote down vote up
function matchDate(day: Date, matcher: Modifier): boolean {
  if (!(matcher instanceof Date)) return false;
  return isSameDay(day, matcher);
}
Example #9
Source File: Greeting.tsx    From apps with GNU Affero General Public License v3.0 5 votes vote down vote up
export default function Greeting({
  onEnter,
  onExit,
  user,
}: {
  user?: LoggedUser;
  onEnter: () => unknown;
  onExit: () => unknown;
}): ReactElement {
  const [show, setShow] = useState(false);

  const greetingElement = useMemo(() => {
    const firstName = user?.name?.split?.(' ')?.[0];
    const greeting = getGreetingData();
    return (
      <div className="ml-2 font-bold typo-callout">
        {greeting.text}
        {firstName && (
          <span className="hidden laptop:inline">, {firstName}</span>
        )}{' '}
        {greeting.emoji}
      </div>
    );
  }, []);

  useEffect(() => {
    (async () => {
      const media = window.matchMedia(tablet.replace('@media ', ''));
      if (!media.matches) {
        return;
      }

      const now = new Date();
      const lastGreeting = await getCache<Date>('greeting');
      const showGreeting =
        !lastGreeting ||
        !isSameDay(now, lastGreeting) ||
        getGreetingSlot(lastGreeting.getHours()) !==
          getGreetingSlot(now.getHours());
      if (showGreeting) {
        await setCache('greeting', now);
        setTimeout(() => {
          onEnter();
          setTimeout(() => {
            setShow(true);
            setTimeout(() => setShow(false), 7000);
          }, 500);
        }, 1500);
      }
    })();
  }, []);

  return (
    <CSSTransition
      in={show}
      timeout={500}
      classNames="fade"
      unmountOnExit
      onExited={onExit}
    >
      {greetingElement}
    </CSSTransition>
  );
}
Example #10
Source File: habits.ts    From nyxo-app with GNU General Public License v3.0 5 votes vote down vote up
shouldResetDayStreak = ({
  latestCompletedDate
}: Habit): boolean => {
  const today = startOfDay(new Date())
  const lastDate = new Date(latestCompletedDate ?? new Date())
  return !isSameDay(today, lastDate)
}
Example #11
Source File: chartDataHelper.ts    From korona-info with MIT License 5 votes vote down vote up
getTimeSeriesData = (
  confirmed: Confirmed[],
  // recovered: Recovered[],
  deaths: Deaths[]
): TimeSeriesData => {
  const sortedData = sortBy(confirmed, 'date').map(item => ({
    ...item,
    dateString: format(new Date(item.date), 'yyyy-MM-dd')
  }));
  // const sortedDataRecoverd = sortBy(recovered, 'date').map(item => ({
  //   ...item,
  //   dateString: format(new Date(item.date), 'yyyy-MM-dd')
  // }));
  const sortedDataDeaths = sortBy(deaths, 'date').map(item => ({
    ...item,
    dateString: format(new Date(item.date), 'yyyy-MM-dd')
  }));
  const today = new Date();
  const startDate = new Date(sortedData[0]?.date ?? today);
  const days30Ago = subDays(today, 30);
  const daysIntervalSinceFirstInfection = eachDayOfInterval({
    start: startDate.getTime() > days30Ago.getTime() ? days30Ago : startDate,
    end: today
  });

  const infectionDevelopmentData: InfectionDevelopmentDataItem[] = [];
  daysIntervalSinceFirstInfection.reduce(
    (
      acc: {
        // recovered: number;
        infections: number;
        deaths: number;
      },
      curr
    ) => {
      const items = sortedData.filter(item =>
        isSameDay(new Date(item.date), curr)
      );
      // const itemsRecovered = sortedDataRecoverd.filter(item =>
      //   isSameDay(new Date(item.date), curr)
      // );
      const itemsDeaths = sortedDataDeaths.filter(item =>
        isSameDay(new Date(item.date), curr)
      );
      acc.deaths = acc.deaths + itemsDeaths.length;
      acc.infections = acc.infections + items.length;
      // acc.recovered = acc.recovered + itemsRecovered.length;

      infectionDevelopmentData.push({
        date: curr.getTime(),
        infectionsDaily: items.length,
        ...acc
      });

      return acc;
    },
    { infections: 0, deaths: 0 }
  );

  const thirtyDaysAgo = subDays(today, 30);
  const infectionDevelopmentData30Days = infectionDevelopmentData.filter(
    item => item.date > thirtyDaysAgo.getTime()
  );

  return {
    infectionDevelopmentData,
    infectionDevelopmentData30Days
  };
}
Example #12
Source File: MonthlyBody.tsx    From react-calendar with MIT License 5 votes vote down vote up
export function MonthlyBody<DayData>({
  omitDays,
  events,
  children,
}: MonthlyBodyProps<DayData>) {
  let { days, locale } = useMonthlyCalendar();
  let { headings, daysToRender, padding } = handleOmittedDays({
    days,
    omitDays,
    locale,
  });

  let headingClassName =
    'rc-border-b-2 rc-p-2 rc-border-r-2 lg:rc-block rc-hidden';
  return (
    <div className="rc-bg-white rc-border-l-2 rc-border-t-2">
      <div
        className={`rc-grid rc-grid-cols-1 sm:rc-grid-cols-2 md:rc-grid-cols-4 ${
          //@ts-ignore
          headingClasses[`l${headings.length}`]
        }`}
      >
        {headings.map(day => (
          <div
            key={day.day}
            className={headingClassName}
            aria-label="Day of Week"
          >
            {day.label}
          </div>
        ))}
        {padding.map((_, index) => (
          <div
            key={index}
            className={headingClassName}
            aria-label="Empty Day"
          />
        ))}
        {daysToRender.map(day => (
          <MonthlyBodyContext.Provider
            key={day.toISOString()}
            value={{
              day,
              events: events.filter(data => isSameDay(data.date, day)),
            }}
          >
            {children}
          </MonthlyBodyContext.Provider>
        ))}
      </div>
    </div>
  );
}
Example #13
Source File: InterestSection.tsx    From anchor-web-app with Apache License 2.0 4 votes vote down vote up
export function InterestSection({ className }: InterestSectionProps) {
  const { constants } = useAnchorWebapp();

  const { data: { apyHistory } = {} } = useEarnAPYHistoryQuery();
  const { data: { overseerEpochState, overseerConfig } = {} } =
    useEarnEpochStatesQuery();

  const apy = useDepositApy();

  const { data: earnApyProjection } = useEarnApyProjectionQuery();

  const apyChartItems = useMemo<APYChartItem[] | undefined>(() => {
    const history = apyHistory
      ?.map(({ Timestamp, DepositRate }) => ({
        date: new Date(Timestamp * 1000),
        value: computeApy(
          DepositRate,
          constants.blocksPerYear,
          overseerConfig?.epoch_period ?? 1,
        ).toNumber() as Rate<number>,
      }))
      .reverse();

    return history && overseerEpochState
      ? [
          ...history,
          ...(history.length === 0 || isSameDay(history[0].date, new Date())
            ? [
                {
                  date: new Date(),
                  value: apy.toNumber() as Rate<number>,
                },
              ]
            : []),
        ]
      : undefined;
  }, [
    apyHistory,
    constants.blocksPerYear,
    apy,
    overseerEpochState,
    overseerConfig,
  ]);

  return (
    <Section className={className}>
      <h2>
        <IconSpan>
          INTEREST <InfoTooltip>Current annualized deposit rate</InfoTooltip>
        </IconSpan>
      </h2>

      <div className="apy">
        <TooltipLabel
          className="name"
          title="Annual Percentage Yield"
          placement="top"
          style={{ border: 'none' }}
        >
          APY
        </TooltipLabel>
        <div className="value">
          <AnimateNumber format={formatRate}>{apy}</AnimateNumber>%
        </div>
        <p
          style={{ opacity: earnApyProjection !== undefined ? 1 : 0 }}
          className="projectedValue"
        >
          {earnApyProjection && (
            <EarnApyProjection
              height={earnApyProjection.height}
              rate={earnApyProjection.rate}
            />
          )}
        </p>
        {apyChartItems && (
          <APYChart
            margin={{ top: 20, bottom: 20, left: 100, right: 100 }}
            gutter={{ top: 30, bottom: 20, left: 100, right: 100 }}
            data={apyChartItems}
            minY={() => -0.03}
            maxY={(...values) => Math.max(...values, 0.3)}
          />
        )}
      </div>
    </Section>
  );
}
Example #14
Source File: DateSelect.tsx    From UUI with MIT License 4 votes vote down vote up
DateSelect = UUIFunctionComponent({
  name: 'DateSelect',
  nodes: {
    Root: 'div',
    Calendar: 'div',
    WeekGrid: 'div',
    WeekItem: 'div',
    DayGrid: 'div',
    DayItem: 'div',
  },
  propTypes: DateSelectPropTypes,
}, (props: DateSelectFeatureProps, { nodes, NodeDataProps }) => {
  const {
    Root, Calendar,
    WeekGrid, WeekItem,
    DayGrid, DayItem,
  } = nodes

  const betweenIncludeDates = useCallback((date: Date, range: [Date, Date] | Date[]) => {
    return !isBefore(date, range[0]) && !isAfter(date, range[1])
  }, [])

  const dateInfo = useMemo(() => {
    const firstDayInMonth = startOfMonth(props.yearMonth)
    const weekdayOfFirstDayInMonth = getDay(firstDayInMonth)

    const weekdays = range(0, 7).map((i) => {
      let date = new Date(props.yearMonth)
      date = startOfWeek(date)
      date = add(date, { days: i })
      return {
        key: format(date, 'yyyy-MM-dd'),
        date: date,
        label: format(date, 'EEEEEE', { locale: zhCN }),
      };
    });

    const days = range(
      1 - weekdayOfFirstDayInMonth,
      1 - weekdayOfFirstDayInMonth + 6*7,
    ).map((i) => {
      const date = add(firstDayInMonth, { days: i - 1 })
      const selected = props.selectedDates.findIndex((i) => isSameDay(date, i)) !== -1
      const inSelectedRange = (() => {
        if (props.selectedDates.length >= 2) {
          return betweenIncludeDates(date, props.selectedDates)
        }
        return false;
      })()
      return {
        key: format(date, 'yyyy-MM-dd'),
        date: date,
        label: getDate(date),
        active: isSameMonth(props.yearMonth, date),
        selected: selected,
        inSelectedRange: inSelectedRange,
      }
    })

    return {
      weekdays,
      days
    }
  }, [props.yearMonth, props.selectedDates, betweenIncludeDates])

  return (
    <Root>
      <Calendar>
        <WeekGrid>
          {dateInfo.weekdays.map((weekday) => {
            return (
              <WeekItem key={weekday.key}>
                {weekday.label}
              </WeekItem>
            );
          })}
        </WeekGrid>
        <DayGrid
          onMouseLeave={() => {
            props.onHoverDateChange && props.onHoverDateChange(undefined)
          }}
        >
          {dateInfo.days.map((day) => {
            const hovering = props.hoverDate ? isSameDay(day.date, props.hoverDate) : false
            const inHoverRange = (() => {
              if (props.selectedDates.length === 1 && props.hoverDate) {
                return betweenIncludeDates(day.date, [props.selectedDates[0], props.hoverDate].sort((i, j) => Number(i) - Number(j)))
              }
              return false
            })()
            return (
              <DayItem
                {...NodeDataProps({
                  'active': day.active,
                  'selected': day.selected,
                  'in-selected-range': day.inSelectedRange,
                  'in-hover-range': inHoverRange,
                  'hovering': hovering,
                })}
                key={day.key}
                onClick={() => {
                  props.onSelect(day.date)
                }}
                onMouseEnter={() => {
                  props.onHoverDateChange && props.onHoverDateChange(day.date)
                }}
                onMouseLeave={() => {
                  props.onHoverDateChange && props.onHoverDateChange(undefined)
                }}
              >
                {day.label}
              </DayItem>
            )
          })}
        </DayGrid>
      </Calendar>
    </Root>
  )
})
Example #15
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>
  )
}