date-fns#startOfWeek TypeScript Examples

The following examples show how to use date-fns#startOfWeek. 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: dateUtils.tsx    From symphony-ui-toolkit with Apache License 2.0 6 votes vote down vote up
/**
 * Return a list of translated weekdays, the starting day depends on locale
 * @param date
 * @param locale
 * @param pattern
 */
function getWeekdays(date: Date, locale: Locale, pattern: string): string[] {
  const arr = eachDayOfInterval({
    start: startOfWeek(date, { locale }),
    end: endOfWeek(date, { locale }),
  });

  return arr.map((item) => {
    return format(item, pattern, { locale });
  });
}
Example #2
Source File: dateUtils.tsx    From symphony-ui-toolkit with Apache License 2.0 6 votes vote down vote up
export function getDaysNeededForLastMonth(date: Date, locale: Locale) {
  const firstDayOfWeek = startOfWeek(date, { locale });

  const startDate = startOfMonth(date);
  // getDay return the value of the weekday from 0 to 6
  // i.e. startDate is a Wednesday -> getDay(startDate) = 3
  // i.e. firstDayOfWeek is a Sunday -> getDay(firstDayOfWeek) = 0 (depends on locale)
  // + 7 and the modulo to ensure the result is positive value is between 0 and 6 (javascript % can return negative value)
  return (getDay(startDate) - getDay(firstDayOfWeek) + 7) % 7;
}
Example #3
Source File: datecalc.ts    From calendar-hack with MIT License 6 votes vote down vote up
export function calcPlanDates(planWeeks: number, planEndsOn: Date): PlanDates {
    const end = startOfDay(endOfWeek(planEndsOn, { weekStartsOn: 1 }));
    const planStart = subDays(planEndsOn, planWeeks * 7 - 1);
    const start = startOfWeek(planStart, { weekStartsOn: 1 });
    const totalDays = 1 + differenceInCalendarDays(end, start);
    if (0 !== totalDays % 7) {
        throw new Error("total days %7 !==0: " + totalDays);
    }
    const weekCount = totalDays / 7;
    let result = {
        start: start,
        planStartDate: planStart,
        planEndDate: planEndsOn, // before or on race day
        end: end, // race day or beyond
        weekCount: weekCount
    }
    return result;
}
Example #4
Source File: dategrid.ts    From calendar-hack with MIT License 6 votes vote down vote up
setEvent(date: Date, event: T | undefined) {
        const k = key(date);
        if (event) {
            this._events.set(k, event);
            // min/max/first/last/weekCount maintenance
            if (!this._max || isAfter(date, this._max))
                this._max = date;
            this._last = startOfDay(endOfWeek(this._max, { weekStartsOn: 1 }))
            if (!this._min || isBefore(date, this._min))
                this._min = date;
            this._first = startOfWeek(this._min, { weekStartsOn: 1 })
            this._weekCount = differenceInWeeks(startOfDay(addDays(this._last, 1)), this._first);
        } else {
            this._events.delete(k);
        }
    }
Example #5
Source File: WeeklyCalendar.tsx    From react-calendar with MIT License 6 votes vote down vote up
WeeklyCalendar = ({
  locale,
  week,
  children,
}: WeeklyCalendarProps) => {
  let [selectedDay, setSelectedDay] = useState<Date>();

  //clear the selected day if the week changes
  useEffect(() => {
    setSelectedDay(undefined);
  }, [week]);

  return (
    <WeeklyContext.Provider
      value={{
        locale,
        selectedDay,
        week: startOfWeek(week),
        changeSelectedDay: setSelectedDay,
      }}
    >
      {children}
    </WeeklyContext.Provider>
  );
}
Example #6
Source File: DayPicker.tsx    From symphony-ui-toolkit with Apache License 2.0 5 votes vote down vote up
handleKeyDownCell(e: React.KeyboardEvent, date: Date, modifers): void {
    const { locale, dir } = this.props;
    const { currentMonth } = this.state;
    if (e.key !== Keys.ESC) {
      cancelEvent(e);
    }

    const direction = dir === 'ltr' ? 1 : -1;
    const MAX_STEP_TO_CHECK = 7;
    let nextCell;
    switch (e.key) {
    case Keys.TAB:
      if (this.dayPicker) {
        if (e.shiftKey) {
          this.dayPicker
            .querySelector('.tk-daypicker-header--nextYear')
            .focus();
        } else {
          this.dayPicker.querySelector('.tk-daypicker-today').focus();
        }
      }
      break;
    case Keys.SPACE:
    case Keys.SPACEBAR:
    case Keys.ENTER:
      // eslint-disable-next-line no-case-declarations
      const { onDayClick } = this.props;
      onDayClick(date, modifers);
      break;
    case Keys.PAGE_UP:
      if (e.shiftKey) {
        this.monthNavigation(date, addYears(currentMonth, -1));
      } else {
        this.monthNavigation(date, addMonths(currentMonth, -1));
      }
      break;
    case Keys.PAGE_DOWN:
      if (e.shiftKey) {
        this.monthNavigation(date, addYears(currentMonth, 1));
      } else {
        this.monthNavigation(date, addMonths(currentMonth, 1));
      }
      break;
    case Keys.HOME:
      // eslint-disable-next-line no-case-declarations
      const firstDayOfWeek = startOfWeek(date, { locale });
      nextCell =
          firstDayOfWeek.getDate() <= date.getDate()
            ? firstDayOfWeek
            : startOfMonth(date);
      this.focusOnlyEnabledCell(nextCell, 'next', MAX_STEP_TO_CHECK);
      break;
    case Keys.END:
      // eslint-disable-next-line no-case-declarations
      const lastDayOfWeek = endOfWeek(date, { locale });
      nextCell =
          date.getDate() <= lastDayOfWeek.getDate()
            ? lastDayOfWeek
            : lastDayOfMonth(date);
      this.focusOnlyEnabledCell(nextCell, 'previous', MAX_STEP_TO_CHECK);
      break;
    case Keys.ARROW_LEFT:
      this.arrowNavigation(date, addDays(date, -1 * direction));
      break;
    case Keys.ARROW_UP:
      this.arrowNavigation(date, addDays(date, -7));
      break;
    case Keys.ARROW_RIGHT:
      this.arrowNavigation(date, addDays(date, 1 * direction));
      break;
    case Keys.ARROW_DOWN:
      this.arrowNavigation(date, addDays(date, 7));
      break;
    default:
      break;
    }
  }
Example #7
Source File: dateUtils.tsx    From symphony-ui-toolkit with Apache License 2.0 5 votes vote down vote up
export function getFirstDayOfWeek(date: Date, locale: Locale) {
  return getDay(startOfWeek(date, { locale }));
}
Example #8
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 #9
Source File: DateRangePicker.stories.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
StaticDisabledDate: Story<StaticDateRangePickerProps> = () => {
  const disabledDate = (date: Date) => isEqual(startOfWeek(date), startOfDay(date))
  return <DateRangePicker.Static
    disabledDate={disabledDate}
  />
}
Example #10
Source File: dates.ts    From office-booker with MIT License 5 votes vote down vote up
dateStartOfWeek = (date: string) => {
  const start = startOfWeek(parse(date, 'yyyy-MM-dd', new Date()), { weekStartsOn: 1 });
  const adjustedToUTC = subMinutes(start, start.getTimezoneOffset());
  return format(adjustedToUTC, 'yyyy-MM-dd');
}
Example #11
Source File: booking.test.ts    From office-booker with MIT License 5 votes vote down vote up
nextMonday = startOfWeek(addWeeks(new Date(), 1), { weekStartsOn: 1 })
Example #12
Source File: date.ts    From ngx-gantt with MIT License 5 votes vote down vote up
startOfWeek(options?: { locale?: Locale; weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 }): GanttDate {
        return new GanttDate(startOfWeek(this.value, options));
    }
Example #13
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 #14
Source File: VisitorListAside.tsx    From ra-enterprise-demo with MIT License 4 votes vote down vote up
Aside: FC = () => (
    <Card>
        <CardContent>
            <FilterLiveSearch />
            <span id="persisted-queries">
                <SavedQueriesList />
            </span>
            <FilterList
                label="resources.customers.filters.last_visited"
                icon={<AccessTimeIcon />}
            >
                <FilterListItem
                    label="resources.customers.filters.today"
                    value={{
                        last_seen_gte: endOfYesterday().toISOString(),
                        last_seen_lte: undefined,
                    }}
                />
                <FilterListItem
                    label="resources.customers.filters.this_week"
                    value={{
                        last_seen_gte: startOfWeek(new Date()).toISOString(),
                        last_seen_lte: undefined,
                    }}
                />
                <FilterListItem
                    label="resources.customers.filters.last_week"
                    value={{
                        last_seen_gte: subWeeks(
                            startOfWeek(new Date()),
                            1
                        ).toISOString(),
                        last_seen_lte: startOfWeek(new Date()).toISOString(),
                    }}
                />
                <FilterListItem
                    label="resources.customers.filters.this_month"
                    value={{
                        last_seen_gte: startOfMonth(new Date()).toISOString(),
                        last_seen_lte: undefined,
                    }}
                />
                <FilterListItem
                    label="resources.customers.filters.last_month"
                    value={{
                        last_seen_gte: subMonths(
                            startOfMonth(new Date()),
                            1
                        ).toISOString(),
                        last_seen_lte: startOfMonth(new Date()).toISOString(),
                    }}
                />
                <FilterListItem
                    label="resources.customers.filters.earlier"
                    value={{
                        last_seen_gte: undefined,
                        last_seen_lte: subMonths(
                            startOfMonth(new Date()),
                            1
                        ).toISOString(),
                    }}
                />
            </FilterList>

            <FilterList
                label="resources.customers.filters.has_ordered"
                icon={<MonetizationOnIcon />}
            >
                <FilterListItem
                    label="ra.boolean.true"
                    value={{
                        nb_commands_gte: 1,
                        nb_commands_lte: undefined,
                    }}
                />
                <FilterListItem
                    label="ra.boolean.false"
                    value={{
                        nb_commands_gte: undefined,
                        nb_commands_lte: 0,
                    }}
                />
            </FilterList>

            <FilterList
                label="resources.customers.filters.has_newsletter"
                icon={<MailIcon />}
            >
                <FilterListItem
                    label="ra.boolean.true"
                    value={{ has_newsletter: true }}
                />
                <FilterListItem
                    label="ra.boolean.false"
                    value={{ has_newsletter: false }}
                />
            </FilterList>

            <FilterList
                label="resources.customers.filters.group"
                icon={<LocalOfferIcon />}
            >
                {segments.map(segment => (
                    <FilterListItem
                        label={segment.name}
                        key={segment.id}
                        value={{ groups: segment.id }}
                    />
                ))}
            </FilterList>
        </CardContent>
    </Card>
)