date-fns#getYear TypeScript Examples

The following examples show how to use date-fns#getYear. 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: FakeAppointmentsRepository.ts    From gobarber-api with MIT License 6 votes vote down vote up
public async findAllInMonthFromProvider({
    provider_id,
    month,
    year,
  }: IFindAllInMonthFromProviderDTO): Promise<Appointment[]> {
    const appointments = this.appointments.filter(appointment => {
      return (
        appointment.provider_id === provider_id &&
        getMonth(appointment.date) + 1 === month &&
        getYear(appointment.date) === year
      );
    });

    return appointments;
  }
Example #2
Source File: FakeAppointmentsRepository.ts    From gobarber-api with MIT License 6 votes vote down vote up
public async findAllInDayFromProvider({
    provider_id,
    day,
    month,
    year,
  }: IFindAllInDayFromProviderDTO): Promise<Appointment[]> {
    const appointments = this.appointments.filter(appointment => {
      return (
        appointment.provider_id === provider_id &&
        getDate(appointment.date) === day &&
        getMonth(appointment.date) + 1 === month &&
        getYear(appointment.date) === year
      );
    });

    return appointments;
  }
Example #3
Source File: FakeAppointmentsRepository.ts    From hotseat-api with MIT License 6 votes vote down vote up
public async findByMonthFromProvider({
    provider_id,
    year,
    month,
  }: IFindByMonthFromProviderDTO): Promise<Appointment[]> {
    const appointments = this.appointments.filter(
      appointment =>
        appointment.provider_id === provider_id &&
        getMonth(appointment.date) === month &&
        getYear(appointment.date) === year,
    );

    return appointments;
  }
Example #4
Source File: FakeAppointmentsRepository.ts    From hotseat-api with MIT License 6 votes vote down vote up
public async findByDayFromProvider({
    provider_id,
    day,
    month,
    year,
  }: IFindByDayFromProviderDTO): Promise<Appointment[]> {
    const appointments = this.appointments.filter(
      appointment =>
        appointment.provider_id === provider_id &&
        getDate(appointment.date) === day &&
        getMonth(appointment.date) === month &&
        getYear(appointment.date) === year,
    );

    return appointments;
  }
Example #5
Source File: FakeAppointmentsRepository.ts    From gobarber-project with MIT License 6 votes vote down vote up
public async findAllInMonthFromProvider({
    provider_id,
    month,
    year,
  }: IFindAllInMonthFromProviderDTO): Promise<Appointment[]> {
    const appointments = this.appointments.filter(appointment => {
      return (
        appointment.provider_id === provider_id &&
        getMonth(appointment.date) + 1 === month &&
        getYear(appointment.date) === year
      );
    });

    return appointments;
  }
Example #6
Source File: FakeAppointmentsRepository.ts    From gobarber-project with MIT License 6 votes vote down vote up
public async findAllInDayFromProvider({
    provider_id,
    day,
    month,
    year,
  }: IFindAllInDayFromProviderDTO): Promise<Appointment[]> {
    const appointments = this.appointments.filter(appointment => {
      return (
        appointment.provider_id === provider_id &&
        getDate(appointment.date) === day &&
        getMonth(appointment.date) + 1 === month &&
        getYear(appointment.date) === year
      );
    });

    return appointments;
  }
Example #7
Source File: FakeAppointmentsRepository.ts    From GoBarber with MIT License 6 votes vote down vote up
public async findAllInMonthFromProvider({
    provider_id,
    month,
    year,
  }: IFindAllInMonthFromProviderDTO): Promise<Appointment[]> {
    const appointments = this.appointments.filter(
      appointment =>
        appointment.provider_id === provider_id &&
        getMonth(appointment.date) + 1 === month &&
        getYear(appointment.date) === year,
    );

    return appointments;
  }
Example #8
Source File: FakeAppointmentsRepository.ts    From GoBarber with MIT License 6 votes vote down vote up
public async findAllInDayFromProvider({
    provider_id,
    day,
    month,
    year,
  }: IFindAllInDayFromProviderDTO): Promise<Appointment[]> {
    const appointments = this.appointments.filter(
      appointment =>
        appointment.provider_id === provider_id &&
        getDate(appointment.date) === day &&
        getMonth(appointment.date) + 1 === month &&
        getYear(appointment.date) === year,
    );

    return appointments;
  }
Example #9
Source File: ngx-mat-datefns-date-adapter.ts    From ngx-mat-datefns-date-adapter with MIT License 6 votes vote down vote up
/** Creates a date but allows the month and date to overflow. */
  private _createDateWithOverflow(year: number, month: number, date: number) {
    const result = this._createDateInternal(year, month, date);

    // We need to correct for the fact that JS native Date treats years in range [0, 99] as
    // abbreviations for 19xx.
    if (year >= 0 && year < 100) {
      result.setFullYear(this.getYear(result) - 1900);
    }
    return result;
  }
Example #10
Source File: MonthlyCalendar.tsx    From react-calendar with MIT License 6 votes vote down vote up
MonthlyNav = () => {
  let { locale, currentMonth, onCurrentMonthChange } = useMonthlyCalendar();

  return (
    <div className="rc-flex rc-justify-end rc-mb-4">
      <button
        onClick={() => onCurrentMonthChange(subMonths(currentMonth, 1))}
        className="rc-cursor-pointer"
      >
        Previous
      </button>
      <div
        className="rc-ml-4 rc-mr-4 rc-w-32 rc-text-center"
        aria-label="Current Month"
      >
        {format(
          currentMonth,
          getYear(currentMonth) === getYear(new Date()) ? 'LLLL' : 'LLLL yyyy',
          { locale }
        )}
      </div>
      <button
        onClick={() => onCurrentMonthChange(addMonths(currentMonth, 1))}
        className="rc-cursor-pointer"
      >
        Next
      </button>
    </div>
  );
}
Example #11
Source File: ngx-mat-datefns-date-adapter.ts    From ngx-mat-datefns-date-adapter with MIT License 5 votes vote down vote up
getYear(date: Date): number {
    return getYear(date);
  }
Example #12
Source File: index.tsx    From taskcafe with MIT License 4 votes vote down vote up
DueDateManager: React.FC<DueDateManagerProps> = ({ task, onDueDateChange, onRemoveDueDate, onCancel }) => {
  const currentDueDate = task.dueDate.at ? dayjs(task.dueDate.at).toDate() : null;
  const {
    register,
    handleSubmit,
    setValue,
    setError,
    formState: { errors },
    control,
  } = useForm<DueDateFormData>();

  const [startDate, setStartDate] = useState<Date | null>(currentDueDate);
  const [endDate, setEndDate] = useState<Date | null>(currentDueDate);
  const [hasTime, enableTime] = useState(task.hasTime ?? false);

  const years = _.range(2010, getYear(new Date()) + 10, 1);
  const months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December',
  ];

  const [isRange, setIsRange] = useState(false);
  const [notDuration, setNotDuration] = useState(10);
  const [removedNotifications, setRemovedNotifications] = useState<Array<string>>([]);
  const [notifications, setNotifications] = useState<Array<NotificationInternal>>(
    task.dueDate.notifications
      ? task.dueDate.notifications.map((c, idx) => {
          const duration =
            notificationPeriodOptions.find((o) => o.value === c.duration.toLowerCase()) ?? notificationPeriodOptions[0];
          return {
            internalId: `n${idx}`,
            externalId: c.id,
            period: c.period,
            duration,
          };
        })
      : [],
  );
  return (
    <Wrapper>
      <DateRangeInputs>
        <DatePicker
          selected={startDate}
          onChange={(date) => {
            if (!Array.isArray(date) && date !== null) {
              setStartDate(date);
            }
          }}
          popperClassName="picker-hidden"
          dateFormat="yyyy-MM-dd"
          disabledKeyboardNavigation
          placeholderText="Select due date"
        />
        {isRange ? (
          <DatePicker
            selected={startDate}
            onChange={(date) => {
              if (!Array.isArray(date)) {
                setStartDate(date);
              }
            }}
            popperClassName="picker-hidden"
            dateFormat="yyyy-MM-dd"
            placeholderText="Select from date"
          />
        ) : (
          <AddDateRange>Add date range</AddDateRange>
        )}
      </DateRangeInputs>
      <DatePicker
        selected={startDate}
        onChange={(date) => {
          if (!Array.isArray(date)) {
            setStartDate(date);
          }
        }}
        startDate={startDate}
        useWeekdaysShort
        renderCustomHeader={({
          date,
          changeYear,
          changeMonth,
          decreaseMonth,
          increaseMonth,
          prevMonthButtonDisabled,
          nextMonthButtonDisabled,
        }) => (
          <HeaderActions>
            <HeaderButton onClick={decreaseMonth} disabled={prevMonthButtonDisabled}>
              Prev
            </HeaderButton>
            <HeaderSelectLabel>
              {months[date.getMonth()]}
              <HeaderSelect
                value={months[getMonth(date)]}
                onChange={({ target: { value } }) => changeMonth(months.indexOf(value))}
              >
                {months.map((option) => (
                  <option key={option} value={option}>
                    {option}
                  </option>
                ))}
              </HeaderSelect>
            </HeaderSelectLabel>
            <HeaderSelectLabel>
              {date.getFullYear()}
              <HeaderSelect value={getYear(date)} onChange={({ target: { value } }) => changeYear(parseInt(value, 10))}>
                {years.map((option) => (
                  <option key={option} value={option}>
                    {option}
                  </option>
                ))}
              </HeaderSelect>
            </HeaderSelectLabel>

            <HeaderButton onClick={increaseMonth} disabled={nextMonthButtonDisabled}>
              Next
            </HeaderButton>
          </HeaderActions>
        )}
        inline
      />
      <ActionsSeparator />
      {hasTime && (
        <ActionsWrapper>
          <ActionClock width={16} height={16} />
          <ActionLabel>Due Time</ActionLabel>
          <DatePicker
            selected={startDate}
            onChange={(date) => {
              if (!Array.isArray(date)) {
                setStartDate(date);
              }
            }}
            showTimeSelect
            showTimeSelectOnly
            timeIntervals={15}
            timeCaption="Time"
            dateFormat="h:mm aa"
          />
          <ActionIcon onClick={() => enableTime(false)}>
            <Cross width={16} height={16} />
          </ActionIcon>
        </ActionsWrapper>
      )}
      {notifications.map((n, idx) => (
        <ActionsWrapper key={n.internalId}>
          <NotificationEntry
            notification={n}
            onChange={(period, duration) => {
              setNotifications((prev) =>
                produce(prev, (draft) => {
                  draft[idx].duration = duration;
                  draft[idx].period = period;
                }),
              );
            }}
            onRemove={() => {
              setNotifications((prev) =>
                produce(prev, (draft) => {
                  draft.splice(idx, 1);
                  if (n.externalId !== null) {
                    setRemovedNotifications((prev) => {
                      if (n.externalId !== null) {
                        return [...prev, n.externalId];
                      }
                      return prev;
                    });
                  }
                }),
              );
            }}
          />
        </ActionsWrapper>
      ))}
      <ControlWrapper>
        <LeftWrapper>
          <SaveButton
            onClick={() => {
              if (startDate && notifications.findIndex((n) => Number.isNaN(n.period)) === -1) {
                onDueDateChange(task, startDate, hasTime, { current: notifications, removed: removedNotifications });
              }
            }}
          >
            Save
          </SaveButton>
          {currentDueDate !== null && (
            <ActionIcon
              onClick={() => {
                onRemoveDueDate(task);
              }}
            >
              <Trash width={16} height={16} />
            </ActionIcon>
          )}
        </LeftWrapper>
        <RightWrapper>
          <ActionIcon
            disabled={notifications.length === 3}
            onClick={() => {
              setNotifications((prev) => [
                ...prev,
                {
                  externalId: null,
                  internalId: `n${prev.length + 1}`,
                  duration: notificationPeriodOptions[0],
                  period: 10,
                },
              ]);
            }}
          >
            <Bell width={16} height={16} />
            <ActionPlus width={8} height={8} />
          </ActionIcon>
          {!hasTime && (
            <ActionIcon
              onClick={() => {
                if (startDate === null) {
                  const today = new Date();
                  today.setHours(12, 30, 0);
                  setStartDate(today);
                }
                enableTime(true);
              }}
            >
              <Clock width={16} height={16} />
            </ActionIcon>
          )}
        </RightWrapper>
      </ControlWrapper>
    </Wrapper>
  );
}
Example #13
Source File: WeekTimeline.tsx    From life-calendar with MIT License 4 votes vote down vote up
transformData = (data: any = { events: [] }) => {
  const _data = JSON.parse(JSON.stringify(data));

  let firstEvent: any = {
    ...DefaultData.events[0],
    _date: parseDate(DefaultData.events[0].date)
  }; // default 1st event (as the "base" event)
  _data.events = _data.events || [];

  // for each item, calculate and append more properties:
  _data.events = _data.events.map((item: any, idx: number) => {
    item._date = parseDate(item.date);
    if (idx === 0) {
      firstEvent = { ...item };
      item._weekNum = 0;
    } else {
      item._weekNum = differenceInWeeks(item._date, firstEvent._date);
    }
    return item;
  });
  // append "Today" to the _data.events (as the last event)
  const now = new Date();
  _data.events.push({
    title: `Today`,
    type: 0,
    date: format(now, 'yyyy-MM-dd'),
    _date: now,
    _weekNum: differenceInWeeks(now, firstEvent._date)
  });

  const firstYear = getYear(firstEvent._date);
  let markedWeeks = []; // highlighted boxes - [0, 52, 104, ...] for 90 years
  let weeks = 0;
  for (let i = 0; i < 90; i += 1) {
    const year = firstYear + i;
    weeks = weeks + (isLeapYear(year) ? 52.28571 : 52.14286);

    let markedWeek = Math.round(weeks);
    // adjust for better alignment (because of Math.round and leap years)
    markedWeek++;
    if (
      [
        4,
        5,
        6,
        11,
        12,
        13,
        18,
        19,
        20,
        25,
        26,
        27,
        32,
        33,
        34,
        39,
        40,
        41,
        46,
        47,
        48,
        53,
        54,
        55,
        60,
        61,
        62,
        67,
        68,
        69,
        74,
        75,
        76,
        81,
        82,
        83,
        88,
        89,
        90
      ].indexOf(i + 1) >= 0
    ) {
      markedWeek = markedWeek - 1;
    }
    markedWeeks.push(markedWeek); // TODO: rounding leads to inaccurate box position
  }
  // console.log('markedWeeks', markedWeeks);

  return [_data, markedWeeks];
}
Example #14
Source File: Footer.tsx    From subscan-multisig-react with Apache License 2.0 4 votes vote down vote up
export function Footer({ className = '' }: { networkConfig?: NetConfigV2; className?: string }) {
  const { t } = useTranslation();
  const { network, chain } = useApi();

  const contactIcons = useMemo(
    () => [
      { href: 'https://twitter.com/subscan_io/', icon: 'twitter-black' },
      {
        href: 'https://riot.im/app/#/room/!uaYUrKBueiKUurHliJ:matrix.org?via=matrix.org&via=matrix.parity.io&via=web3.foundation',
        icon: 'riot-black',
      },
      { href: 'https://github.com/itering/subscan-multisig-react', icon: 'github-black' },
      { href: 'https://medium.com/subscan', icon: 'medium-black' },
      { href: 'mailto:[email protected]', icon: 'email-black' },
    ],
    []
  );
  return (
    <Layout.Footer
      className={`flex flex-col md:flex-row md:items-center md:justify-between lg:px-40 px-2 text-gray-400 z-10 md:fixed bottom-0 left-0 right-0 md:py-6 py-2 ${className}`}
      style={{ background: '#2d2d2d' }}
    >
      <div className="md:flex md:gap-4 md:flex-wrap text-gray-400">
        <span>{t('copy_right', { year: getYear(new Date()) })}</span>
        <a href="https://www.subscan.io/privacy" className="text-gray-400 hover:text-gray-100">
          {t('privacy_policy')}
        </a>
        <a href="https://www.subscan.io/term" className="text-gray-400 hover:text-gray-100">
          {t('term_of_use')}
        </a>
      </div>

      <div className="flex items-center justify-between md:mt-0 mt-2 gap-4">
        <Dropdown
          arrow
          placement="topCenter"
          overlay={
            <Menu>
              {chain && (
                <Menu.Item>
                  <div className="flex flex-col items-center text-blue-400 hover:text-blue-600">
                    <span>
                      {t('donate_unit', { unit: chain.tokens.length > 0 ? chain.tokens[0].symbol : 'Unknown' })}
                    </span>
                    <span>{getDonateAddress(chain.ss58Format)}</span>
                  </div>
                </Menu.Item>
              )}

              <Menu.Item className="text-center text-blue-400 hover:text-blue-600">
                <a href="https://www.subscan.io/donate" target="__blank">
                  {t('donate_other')}
                </a>
              </Menu.Item>
            </Menu>
          }
        >
          <Typography.Link
            target="__blank"
            rel="noopener"
            className="bg-white flex items-center justify-center rounded opacity-40"
            style={{ width: 30, height: 30 }}
          >
            <img src={`/icons/donate.svg`} className="w-6 h-6" />
          </Typography.Link>
        </Dropdown>

        {contactIcons.map(({ href, icon }) => (
          <Typography.Link
            target="__blank"
            rel="noopener"
            href={href}
            key={icon}
            className="bg-white flex items-center justify-center rounded opacity-40"
            style={{ width: 30, height: 30 }}
          >
            <img src={`/icons/${icon}.svg`} className="w-4 h-4" />
          </Typography.Link>
        ))}

        <Language />

        <ThemeSwitch network={network} />
      </div>
    </Layout.Footer>
  );
}