date-fns#startOfHour TypeScript Examples

The following examples show how to use date-fns#startOfHour. 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: 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 #2
Source File: Metrics.tsx    From mStable-apps with GNU Lesser General Public License v3.0 6 votes vote down vote up
DATE_RANGES: State<never>['dates'] = [
  {
    dateRange: DateRange.Day,
    period: TimeMetricPeriod.Hour,
    label: '24 hour',
    from: startOfHour(subHours(new Date(), 23)),
    end: END_OF_HOUR,
  },
  {
    dateRange: DateRange.Week,
    period: TimeMetricPeriod.Day,
    label: '7 day',
    from: startOfDay(subDays(new Date(), 6)),
    end: END_OF_DAY,
  },
  {
    dateRange: DateRange.Month,
    period: TimeMetricPeriod.Day,
    label: '30 day',
    from: startOfDay(subDays(new Date(), 29)),
    end: END_OF_DAY,
  },
  {
    dateRange: DateRange.Days90,
    period: TimeMetricPeriod.Day,
    label: '90 day',
    from: startOfDay(subDays(new Date(), 90)),
    end: END_OF_DAY,
  },
]
Example #3
Source File: CreateAppointmentService.ts    From gobarber-api with MIT License 5 votes vote down vote up
public async execute({
    date,
    provider_id,
    user_id,
  }: IRequest): Promise<Appointment> {
    const appointmentDate = startOfHour(date);

    if (isBefore(appointmentDate, Date.now())) {
      throw new AppError("You cant't create an appointment on past date");
    }

    if (user_id === provider_id) {
      throw new AppError("You can't create an appointment with yourself");
    }

    if (getHours(appointmentDate) < 8 || getHours(appointmentDate) > 17) {
      throw new AppError(
        'You can only create appointments between 8am and 5pm',
      );
    }

    const findAppointmentInSameDate = await this.appointmentsRepository.findByDate(
      {
        date: appointmentDate,
        provider_id,
      },
    );

    if (findAppointmentInSameDate) {
      throw new AppError('This appointment is already booked');
    }

    const appointment = await this.appointmentsRepository.create({
      user_id,
      provider_id,
      date: appointmentDate,
    });

    const dateFormated = format(appointmentDate, "dd/MM/yyyy 'às' HH:mm'h'");

    await this.notificationsRepository.create({
      recipient_id: provider_id,
      content: `Novo agendamento para dia ${dateFormated}.`,
    });

    await this.cacheProvider.invalidate(
      `provider-appointments:${provider_id}:${format(
        appointmentDate,
        'yyyy-M-d',
      )}`,
    );

    return appointment;
  }
Example #4
Source File: CreateAppointmentService.ts    From hotseat-api with MIT License 5 votes vote down vote up
public async execute({
    provider_id,
    customer_id,
    date,
    type,
  }: IRequest): Promise<Appointment> {
    const appointmentDate = startOfHour(date);

    const appointmentInTheSameDate = await this.appointmentsRepository.findByDate(
      appointmentDate,
    );

    if (
      appointmentInTheSameDate &&
      appointmentInTheSameDate.provider_id === provider_id
    ) {
      throw new AppError("There's already a appointment booked in that date");
    }

    const customerIsTheProvider = provider_id === customer_id;

    if (customerIsTheProvider) {
      throw new AppError("You can't book an appointment with yourself");
    }

    const hasValidDate = isAfter(appointmentDate, new Date(Date.now()));

    if (!hasValidDate) {
      throw new AppError("You can't book an appointment in a past date");
    }

    const appointmentHours = getHours(appointmentDate);
    const isInBusinessHoursRange =
      appointmentHours >= BUSINESS_START_HOUR &&
      appointmentHours <= BUSINESS_LIMIT_HOUR;

    if (!isInBusinessHoursRange) {
      throw new AppError(
        "You can't book an appointment in a hour outside the business hours range",
      );
    }

    const appointment = this.appointmentsRepository.create({
      provider_id,
      customer_id,
      date: appointmentDate,
      type,
    });

    const notificationAppointmentDate = format(
      appointmentDate,
      'dd-MM-yyyy HH:mm',
    );

    await this.notificationsRepository.create({
      content: `You have an appointment schedule to ${notificationAppointmentDate}`,
      recipient_id: provider_id,
    });

    this.cacheProvider.invalidate(
      getProviderAppointmentsListCacheKey(provider_id, appointmentDate),
    );

    return appointment;
  }
Example #5
Source File: dateUtils.ts    From ant-extensions with MIT License 5 votes vote down vote up
parseDate = (dt?: string, rounded?: "start" | "end"): ParsedDate => {
  if (dt && isDate(dt)) {
    return parseISO(dt);
  } else if (dt && isDateLike(dt)) {
    const parts = getDateParts(dt);

    if (parts) {
      const { part, op, diff } = parts;
      const diffNum = parseInt(`${op}${diff}`, 10);
      let date = startOfMinute(new Date());

      switch (part) {
        case DateParts.NOW:
          return date;
        case DateParts.DECADE:
          if (rounded) {
            date = (rounded === "start" ? startOfDecade : endOfDecade)(date);
          }
          return addYears(date, diffNum * 10);
        case DateParts.YEAR:
          if (rounded) {
            date = (rounded === "start" ? startOfYear : endOfYear)(date);
          }
          return addYears(date, diffNum);
        case DateParts.QUARTER:
          if (rounded) {
            date = (rounded === "start" ? startOfQuarter : endOfQuarter)(date);
          }
          return addQuarters(date, diffNum);
        case DateParts.MONTH:
          if (rounded) {
            date = (rounded === "start" ? startOfMonth : endOfMonth)(date);
          }
          return addMonths(date, diffNum);
        case DateParts.WEEK:
          if (rounded) {
            date = (rounded === "start" ? startOfWeek : endOfWeek)(date);
          }
          return addWeeks(date, diffNum);
        case DateParts.DAY:
          if (rounded) {
            date = (rounded === "start" ? startOfDay : endOfDay)(date);
          }
          return addDays(date, diffNum);
        case DateParts.HOUR:
          if (rounded) {
            date = (rounded === "start" ? startOfHour : endOfHour)(date);
          }
          return addHours(date, diffNum);
        case DateParts.MINUTE:
          if (rounded) {
            date = (rounded === "start" ? startOfMinute : endOfMinute)(date);
          }
          return addMinutes(date, diffNum);
      }
    }
  }
  return undefined;
}
Example #6
Source File: CreateAppointmentService.ts    From gobarber-project with MIT License 5 votes vote down vote up
public async execute({
    provider_id,
    user_id,
    date,
  }: IRequest): Promise<Appointment> {
    const appointmentDate = startOfHour(date);

    if (isBefore(appointmentDate, Date.now())) {
      throw new AppError("You can't create an appointment on a past date");
    }

    if (user_id === provider_id) {
      throw new AppError("You can't create an appointment with yourself");
    }

    if (getHours(appointmentDate) < 8 || getHours(appointmentDate) > 17) {
      throw new AppError(
        'You can only create appointments between 8am and 5pm',
      );
    }

    const findAppoitmentInSameDate = await this.appointmentsRepository.findByDate(
      appointmentDate,
      provider_id,
    );

    if (findAppoitmentInSameDate) {
      throw new AppError('This appointment is already booked');
    }

    const appointment = await this.appointmentsRepository.create({
      provider_id,
      user_id,
      date: appointmentDate,
    });

    const dateFormatted = format(appointmentDate, "dd/MM/yyyy 'às' HH:mm'h'");

    await this.notificationsRepository.create({
      recipient_id: provider_id,
      content: `Novo agendamento para dia ${dateFormatted}`,
    });

    await this.cacheProvider.invalidate(
      `provider-appointments:${provider_id}:${format(
        appointmentDate,
        'yyyy-M-d',
      )}`,
    );

    return appointment;
  }
Example #7
Source File: CreateAppointmentService.ts    From GoBarber with MIT License 5 votes vote down vote up
public async execute({
    provider_id,
    user_id,
    date,
  }: IRequest): Promise<Appointment> {
    const appointmentDate = startOfHour(date);

    if (isBefore(appointmentDate, Date.now())) {
      throw new AppError("You can't book appointments in past dates");
    }

    if (provider_id === user_id) {
      throw new AppError("You can't book appointments with yourself");
    }

    if (getHours(appointmentDate) < 8 || getHours(appointmentDate) > 17) {
      throw new AppError("You can't book appointments outside commercial time");
    }

    const findAppointmentInSameDate = await this.appointmentsRepository.findByDate(
      appointmentDate,
      provider_id,
    );

    if (findAppointmentInSameDate) {
      throw new AppError('This appointment is already booked');
    }

    const appointment = await this.appointmentsRepository.create({
      provider_id,
      user_id,
      date: appointmentDate,
    });

    const dateFormatted = format(appointmentDate, "dd/MM/yyyy 'às' HH:mm'h'");

    await this.notificationsRepository.create({
      recipient_id: provider_id,
      content: `Novo agendamento para ${dateFormatted}`,
    });

    await this.cacheProvider.invalidate(
      `provider-appointments:${provider_id}:${format(
        appointmentDate,
        'd-M-yyyy',
      )}`,
    );

    return appointment;
  }