date-fns#startOfToday TypeScript Examples

The following examples show how to use date-fns#startOfToday. 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: DayPicker.tsx    From symphony-ui-toolkit with Apache License 2.0 6 votes vote down vote up
constructor(props) {
    super(props);

    this.state = {
      today: startOfToday(),
      currentMonth: props.month || props.selectedDays || new Date(),
    };

    this.handleKeyDownContainer = this.handleKeyDownContainer.bind(this);
    this.handleKeyDownFooter = this.handleKeyDownFooter.bind(this);
  }
Example #3
Source File: RelativeRangePicker.tsx    From gio-design with Apache License 2.0 6 votes vote down vote up
function RelativeRangePicker({ disabledDate, timeRange, onSelect, onCancel, ...rest }: RangePickerProps) {
  const defaultDates = parseStartAndEndDate(timeRange ?? 'day:2,1');
  const [dates, setDates] = React.useState<[Date, Date]>(defaultDates as [Date, Date]);
  const [endDateHidden, setEndDateHidden] = React.useState<boolean>(isYesterday(dates[1]));
  const inputDisabled = !isNil(disabledDate);
  const handleDisabledDate = (current: Date) =>
    disabledDate?.(current) || isAfter(startOfDay(current), endDateHidden ? startOfYesterday() : startOfToday());
  const handleOnOK = () => {
    onSelect(`day:${differenceInDays(startOfToday(), dates[0]) + 1},${differenceInDays(startOfToday(), dates[1])}`);
  };
  return (
    <InnerRangePanel
      data-testid="relative-range-picker"
      disableOK={!isValid(dates[0]) || !isValid(dates[1])}
      header={<RelativeRangeHeader inputDisabled={inputDisabled} dateRange={dates} onRangeChange={setDates} onModeChange={setEndDateHidden} />}
      body={
        <RelativeRangeBody
          dateRange={dates}
          fixedMode={endDateHidden}
          disabledDate={handleDisabledDate}
          onRangeChange={setDates}
        />
      }
      onCancel={onCancel}
      onOK={handleOnOK}
      {...rest}
    />
  );
}
Example #4
Source File: DatePicker.stories.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
StaticDisabledDate.args = {
  disabledDate: (date: Date) => isBefore(startOfToday(), date),
};
Example #5
Source File: DatePicker.stories.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
StaticViewDate.args = {
  viewDate: addMonths(startOfToday(), 1),
};
Example #6
Source File: DateRangePicker.stories.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
StaticViewDates.args = {
  defaultViewDates: [subMonths(startOfToday(), 1), startOfToday()],
};
Example #7
Source File: PastTimePicker.stories.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
DisabledDate = () => {
  const disabledDate = (current: Date) => differenceInDays(startOfToday(), current) > 31
  return <PastTimePicker onSelect={action('selected value:')} placeholder="时间范围" disabledDate={disabledDate} />;
}
Example #8
Source File: PastTimePicker.stories.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
Since.args = {
  value: `since:${getTime(subDays(startOfToday(), 7))}`,
};
Example #9
Source File: PastTimePicker.stories.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
Absolute.args = {
  value: `abs:${getTime(subMonths(startOfToday(), 1))},${getTime(startOfToday())}`,
  onRangeSelect: (date: any, index: number) => console.log(date, index)
};
Example #10
Source File: PastTimePicker.stories.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
StaticDisabledDate.args = {
  disabledDate: (current: Date) => differenceInDays(startOfToday(), current) > 31,
};
Example #11
Source File: AbsoluteRangePicker.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
function AbsoluteRangePicker({ disabledDate, timeRange, onSelect, onRangeSelect, onCancel }: RangePickerProps) {
  const [dates, setDates] = React.useState<[Date | undefined, Date | undefined]>(parseStartAndEndDate(timeRange));
  const prefixCls = usePrefixCls('range-panel__header');

  const locale = useLocale('StaticPastTimePicker');

  const { startDayText, endDayText, FromText, ToText } = {
    ...defaultLocale,
    ...locale,
  };

  const renderHeader = () => {
    const placeholder = [startDayText, endDayText];
    const dateString = formatDates(dates);
    const dateTexts = dateString?.split('-')?.map((d) => (d === ' ' ? undefined : d)) || [];
    const text = [dateTexts[0] ?? placeholder[0], dateTexts[1] ?? placeholder[1]];
    return <span className={`${prefixCls}__text`}>{`${FromText} ${text[0]} ${ToText} ${text[1]}`}</span>;
  };
  const handleDisabledDate = (current: Date) => disabledDate?.(current) || isAfter(current, startOfToday());
  const handleOnOK = () => {
    onSelect(`abs:${getTime(startOfDay(dates[0] as Date))},${getTime(endOfDay(dates[1] as Date))}`);
  };
  const handleOnSelect = (date: [Date, Date], index: number) => {
    setDates(date);
    onRangeSelect?.(date, index);
  }
  const endDay = dates[1] !== undefined && isValid(dates[1]) ? dates[1] : new Date();
  return (
    <InnerRangePanel
      disableOK={!isValid(dates[0]) || !isValid(dates[1])}
      header={renderHeader()}
      body={
        <StaticDateRangePicker
          defaultViewDates={[subMonths(startOfDay(endDay), 1), startOfDay(endDay)]}
          disabledDate={handleDisabledDate}
          onSelect={handleOnSelect}
          value={dates as [Date, Date]}
        />
      }
      onCancel={onCancel}
      onOK={handleOnOK}
    />
  );
}
Example #12
Source File: RelativeRangeHeader.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
convertDateToDays = (date: Date | undefined, defaultValue: number) =>
  date ? differenceInDays(startOfToday(), startOfDay(date)) : defaultValue
Example #13
Source File: SinceRangePicker.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
function SinceRangePicker({ disabledDate, timeRange, onSelect, onCancel, experimental, ...rest }: RangePickerProps) {
  const endDateKeys = ['today', experimental ? 'yesterday' : undefined];
  const dates = parseStartAndEndDate(timeRange);
  const prefixCls = usePrefixCls('range-panel__header');
  const [startDate, setStartDate] = React.useState<Date | undefined>(dates[0]);
  const [endKey, setEndKey] = React.useState(
    endDateKeys[timeRange && timeRange.split(':')[0] === 'since' ? 0 : 1] || 0
  );
  const locale = useLocale<typeof defaultLocale>('StaticPastTimePicker') || defaultLocale;

  const { startDayText, FromText, toTodayText, toYesterdayText } = {
    ...defaultLocale,
    ...locale,
  };

  const END_DATE_MAPPING: Record<string, string> = {
    today: toTodayText,
    yesterday: toYesterdayText,
  };

  const renderHeader = () => {
    const startDateString = startDate ? format(startDate, DATE_FORMAT) : startDayText;
    return (
      <>
        <span className={`${prefixCls}__text`}>{`${FromText} ${startDateString}`}</span>
        <span className={`${prefixCls}__options`}>
          <Switch
            size="small"
            defaultValue={endKey}
            onChange={(e) => {
              setEndKey(e.target.value);
            }}
          >
            {endDateKeys.map(
              (o: string) =>
                o && (
                  <Switch.Item key={o} value={o}>
                    {END_DATE_MAPPING[o]}
                  </Switch.Item>
                )
            )}
          </Switch>
        </span>
      </>
    );
  };
  const handleDisabledDate = (current: Date) =>
    disabledDate?.(current) || isAfter(current, endKey === 'yesterday' ? startOfYesterday() : startOfToday());

  const handleOnOK = () => {
    onSelect(`${endKey === 'yesterday' ? 'since-lt-today' : 'since'}:${getTime(startOfDay(startDate as Date))}`);
  };
  return (
    <InnerRangePanel
      disableOK={!isValid(startDate)}
      header={renderHeader()}
      body={<DatePicker disabledDate={handleDisabledDate} value={startDate} onSelect={setStartDate} />}
      onCancel={onCancel}
      onOK={handleOnOK}
      {...rest}
    />
  );
}
Example #14
Source File: index.test.tsx    From gio-design with Apache License 2.0 4 votes vote down vote up
describe('Testing StaticDatePicker ', () => {
  it('without params', () => {
    const { container } = render(<StaticDateRangePicker />);
    expect(container.querySelector('div[class="gio-date-range-picker"]')).toBeTruthy();
  });

  it('onPanelChange has onPanelChange', () => {
    const { container } = render(
      <StaticDateRangePicker
        disabledDate={(current: Date) => current.getTime() > new Date().getTime()}
        defaultViewDates={[subMonths(startOfToday(), 1), startOfToday()]}
      />
    );

    fireEvent.click(
      container.querySelector('.gio-date-range-picker__left button[class="gio-picker-header-super-prev-btn"]')
    );

    expect(container.querySelector('div[class="gio-picker-cell-inner"]')).toBeTruthy();

    fireEvent.click(
      container.querySelector('.gio-date-range-picker__right button[class="gio-picker-header-super-next-btn"]')
    );

    expect(container.querySelector('div[class="gio-picker-cell-inner"]')).toBeTruthy();
  });

  it('left right', () => {
    const { container } = render(
      <StaticDateRangePicker defaultValue={[new Date('2022-03-01'), new Date('2022-04-01')]} />
    );

    fireEvent.click(container.querySelector('td[title="2022-04-02"] .gio-picker-cell-inner'));

    fireEvent.click(container.querySelector('td[title="2022-04-11"] .gio-picker-cell-inner'));

    expect(container.querySelector('div[class="gio-picker-cell-inner"]')).toBeTruthy();
  });

  it('has function', () => {
    const { container } = render(
      <StaticDateRangePicker
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        onDateMouseEnter={() => {}}
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        onDateMouseLeave={() => {}}
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        onSelect={() => {}}
        defaultValue={[new Date('2022-03-01'), new Date('2022-04-01')]}
      />
    );

    fireEvent.click(container.querySelector('td[title="2022-04-02"] .gio-picker-cell-inner'));

    fireEvent.mouseEnter(container.querySelector('td[title="2022-04-10"] .gio-picker-cell-inner'));

    fireEvent.mouseLeave(container.querySelector('td[title="2022-04-10"] .gio-picker-cell-inner'));

    fireEvent.click(container.querySelector('td[title="2022-04-11"] .gio-picker-cell-inner'));

    expect(container.querySelector('div[class="gio-picker-cell-inner"]')).toBeTruthy();
  });

  it('not function', () => {
    const { container } = render(
      <StaticDateRangePicker defaultValue={[new Date('2022-03-01'), new Date('2022-04-01')]} />
    );

    fireEvent.mouseEnter(container.querySelector('td[title="2022-04-10"] .gio-picker-cell-inner'));

    fireEvent.mouseLeave(container.querySelector('td[title="2022-04-10"] .gio-picker-cell-inner'));

    expect(container.querySelector('div[class="gio-picker-cell-inner"]')).toBeTruthy();
  });

  it('has defaultViewDates', () => {
    const { container } = render(
      <StaticDateRangePicker defaultValue={[new Date('2022-03-01'), new Date('2022-04-01')]} />
    );

    fireEvent.mouseEnter(container.querySelector('td[title="2022-04-10"] .gio-picker-cell-inner'));

    fireEvent.mouseLeave(container.querySelector('td[title="2022-04-10"] .gio-picker-cell-inner'));

    expect(container.querySelector('div[class="gio-picker-cell-inner"]')).toBeTruthy();
  });
});
Example #15
Source File: RelativeRangeHeader.tsx    From gio-design with Apache License 2.0 4 votes vote down vote up
function RelativeRangeHeader({ dateRange, onRangeChange, onModeChange, inputDisabled = false }: RelativeRangeHeaderProps) {
  const [startDays, setStartDays] = React.useState<number>(convertDateToDays(dateRange[0], 2));
  const [endDays, setEndDays] = React.useState<number>(convertDateToDays(dateRange[1], 1));
  const [endDaysHidden, setEndDaysHidden] = React.useState(endDays === 1);

  const locale = useLocale('StaticPastTimePicker');

  const { lastText, dayText, endDayText, ToText } = {
    ...defaultLocale,
    ...locale,
  };

  const basePrefixCls = usePrefixCls('range-panel__header');
  const setRange = (start: number, end: number) => {
    const startDate = subDays(startOfToday(), start);
    const endDate = subDays(startOfToday(), end);
    onRangeChange([startDate, endDate]);
  };

  const renderDuration = () => {
    const duration = endDays === 1 ? startDays : startDays - endDays;
    return (
      <>
        <span className={`${basePrefixCls}__text`}>{lastText}</span>
        <span className={`${basePrefixCls}__input-number`} data-testid="duration">
          <Input.InputNumber
            disabled={inputDisabled}
            min={1}
            max={9999}
            value={duration}
            onChange={(e) => {
              const value = parseInt(e.target.value, 10);
              if (value && value >= 1 && value <= 9999) {
                setRange(value + (endDays as number) - 1, endDays as number);
              }
            }}
            size="small"
          />
        </span>
        <span className={`${basePrefixCls}__text`}>{dayText}</span>
        <Button
          className={`${basePrefixCls}__button`}
          type="secondary"
          prefix={<PlusOutlined />}
          onClick={() => {
            setEndDaysHidden(false);
            onModeChange(false);
          }}
          size="small"
        >
          {endDayText}
        </Button>
      </>
    );
  };
  const renderRange = () => (
    <>
      <span className={`${basePrefixCls}__text`}>{lastText}</span>
      <span data-testid="end-days">
        <Input.InputNumber
          disabled={inputDisabled}
          min={0}
          className={`${basePrefixCls}__input-number`}
          max={startDays - 1}
          value={endDays}
          onChange={(e) => {
            const value = parseInt(e.target.value, 10);
            if (value && value < startDays) {
              setRange(startDays as number, value as number);
            }
          }}
          size="small"
        />
      </span>
      <span className={`${basePrefixCls}__text`}>{ToText}</span>
      <span data-testid="start-days">
        <Input.InputNumber
          disabled={inputDisabled}
          min={endDays + 1}
          max={10000}
          className={`${basePrefixCls}__input-number`}
          value={startDays + 1}
          onChange={(e) => {
            const value = parseInt(e.target.value, 10);
            if (value && value > endDays) {
              setRange((value as number) - 1, endDays as number);
            }
          }}
          size="small"
        />
      </span>
      <span className={`${basePrefixCls}__text`}>{dayText}</span>
    </>
  );

  React.useEffect(() => {
    const currentEndDays = convertDateToDays(dateRange[1], 1);
    setStartDays(convertDateToDays(dateRange[0], 2));
    setEndDays(currentEndDays);
  }, [dateRange]);

  return endDaysHidden ? renderDuration() : renderRange();
}