date-fns#addWeeks TypeScript Examples

The following examples show how to use date-fns#addWeeks. 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: date.ts    From ngx-gantt with MIT License 6 votes vote down vote up
add(amount: number, unit?: GanttDateUtil) {
        switch (unit) {
            case 'second':
                return new GanttDate(this.value).addSeconds(amount);
            case 'minute':
                return new GanttDate(this.value).addMinutes(amount);
            case 'hour':
                return new GanttDate(this.value).addHours(amount);
            case 'day':
                return new GanttDate(this.value).addDays(amount);
            case 'week':
                return new GanttDate(this.value).addWeeks(amount);
            case 'month':
                return new GanttDate(this.value).addMonths(amount);
            case 'quarter':
                return new GanttDate(this.value).addQuarters(amount);
            case 'year':
                return new GanttDate(this.value).addYears(amount);
            default:
                return new GanttDate(this.value).addSeconds(amount);
        }
    }
Example #2
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 #3
Source File: dategrid.ts    From calendar-hack with MIT License 5 votes vote down vote up
selectWeek(weekNum: number) {
        if (!this.first || !this.last) return []
        const d1 = addWeeks(this.first, weekNum);
        const d2 = addDays(d1, 6);
        return eachDayOfInterval({ start: d1, end: d2 });
    }
Example #4
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 #5
Source File: quickShortcuts.ts    From TidGi-Desktop with Mozilla Public License 2.0 5 votes vote down vote up
quickShortcuts = [
  {
    name: '15 minutes',
    calcDate: () => addMinutes(new Date(), 15),
  },
  {
    name: '30 minutes',
    calcDate: () => addMinutes(new Date(), 30),
  },
  {
    name: '45 minutes',
    calcDate: () => addMinutes(new Date(), 45),
  },
  {
    name: '1 hour',
    calcDate: () => addHours(new Date(), 1),
  },
  {
    name: '2 hours',
    calcDate: () => addHours(new Date(), 2),
  },
  {
    name: '4 hours',
    calcDate: () => addHours(new Date(), 4),
  },
  {
    name: '6 hours',
    calcDate: () => addHours(new Date(), 6),
  },
  {
    name: '8 hours',
    calcDate: () => addHours(new Date(), 8),
  },
  {
    name: '10 hours',
    calcDate: () => addHours(new Date(), 8),
  },
  {
    name: '12 hours',
    calcDate: () => addHours(new Date(), 12),
  },
  {
    name: 'Until tomorrow',
    calcDate: () => addDays(new Date(), 1),
  },
  {
    name: 'Until next week',
    calcDate: () => addWeeks(new Date(), 1),
  },
]
Example #6
Source File: date.ts    From ngx-gantt with MIT License 5 votes vote down vote up
addWeeks(amount: number) {
        return new GanttDate(addWeeks(this.value, amount));
    }
Example #7
Source File: App.tsx    From calendar-hack with MIT License 4 votes vote down vote up
App: React.FC = () => {
  const [{ u, p, d }, setq] = useQueryParams({ u: StringParam, p: StringParam, d: DateParam });
  const [selectedUnits, setSelectedUnits] = useState<Units>((u === 'mi' || u === 'km') ? u : 'mi')
  var [selectedPlan, setSelectedPlan] = useState((p && availablePlansById[p]) ? availablePlansById[p] : availablePlans[0]);
  var [planEndDate, setPlanEndDate] = useState((d && isAfter(d, new Date())) ? d : addWeeks(endOfWeek(new Date(), { weekStartsOn: 1 }), 20));
  var [racePlan, setRacePlan] = useState<RacePlan | undefined>(undefined);
  var [undoHistory, setUndoHistory] = useState([] as RacePlan[]);

  useEffect(() => {
    initialLoad(selectedPlan, planEndDate, selectedUnits);
  }, []);

  const [, forceUpdate] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => {
    // listen for changes to the URL and force the app to re-render
    history.listen(() => {
      forceUpdate();
    });
  }, []);

  const getParams = (units: Units, plan: AvailablePlan, date: Date) => {
    return {
      u: units,
      p: plan.id,
      d: date,
    }
  }

  const initialLoad = async (plan: AvailablePlan, endDate: Date, units: Units) => {
    const racePlan = build(await planRepo.fetch(plan), endDate)
    setRacePlan(racePlan);
    setUndoHistory([...undoHistory, racePlan]);
    setq(getParams(units, plan, endDate));
  }

  const onSelectedPlanChange = async (plan: AvailablePlan) => {
    const racePlan = build(await planRepo.fetch(plan), planEndDate);
    setSelectedPlan(plan);
    setRacePlan(racePlan);
    setUndoHistory([racePlan]);
    setq(getParams(selectedUnits, plan, planEndDate));
  }

  const onSelectedEndDateChange = async (date: Date) => {
    const racePlan = build(await planRepo.fetch(selectedPlan), date);
    setPlanEndDate(date);
    setRacePlan(racePlan);
    setUndoHistory([racePlan]);
    setq(getParams(selectedUnits, selectedPlan, date));
  }

  const onSelectedUnitsChanged = (u: Units) => {
    setSelectedUnits(u);
    setq(getParams(u, selectedPlan, planEndDate));
  }

  function swapDates(d1: Date, d2: Date): void {
    if (racePlan) {
      const newRacePlan = swap(racePlan, d1, d2);
      setRacePlan(newRacePlan);
      setUndoHistory([...undoHistory, newRacePlan]);
    }
  }

  function doSwapDow(dow1: dayOfWeek, dow2: dayOfWeek) {
    if (racePlan) {
      const newRacePlan = swapDow(racePlan, dow1, dow2);
      setRacePlan(newRacePlan);
      setUndoHistory([...undoHistory, newRacePlan]);
    }
  }

  function swapWeeks(w1: number, w2: number): void {
    if (racePlan) {
      racePlan.dateGrid.swapWeeks(w1, w2);
      setRacePlan(racePlan);
      setUndoHistory([...undoHistory, racePlan]);
    }
  }

  function downloadHandler() {
    if (racePlan) {
      const iCalEventsStr = toIcal(racePlan, selectedUnits)
      if (iCalEventsStr) {
        download(iCalEventsStr, "plan", "ics");
      }
    }
  }

  function undoHandler() {
    if (undoHistory?.length >= 0) {
      undoHistory.pop();
    }
    setRacePlan(undoHistory[undoHistory.length - 1]);
  }

  return (
    <ThemeProvider theme={theme}>
      <Toolbar downloadHandler={downloadHandler} />
      <PlanAndDate units={selectedUnits} availablePlans={availablePlans} selectedPlan={selectedPlan} selectedDate={planEndDate}
        dateChangeHandler={onSelectedEndDateChange} selectedPlanChangeHandler={onSelectedPlanChange} unitsChangeHandler={onSelectedUnitsChanged}
        downloadHandler={downloadHandler}
      />
      <SecondToolbar>
        <UnitsDiv>
          <UnitsButtons units={selectedUnits} unitsChangeHandler={onSelectedUnitsChanged} />
        </UnitsDiv>
        <DownloadButton downloadHandler={downloadHandler} />
        <UndoButton disabled={undoHistory.length <= 1} undoHandler={undoHandler} />
      </SecondToolbar>
      <PlanDetailsCard racePlan={racePlan} />
      <MainUI>
        {racePlan && <CalendarGrid racePlan={racePlan} units={selectedUnits} swap={swapDates} swapDow={doSwapDow} swapWeeks={swapWeeks} />}
      </MainUI>
    </ThemeProvider>
  )
}
Example #8
Source File: WeekTimeline.tsx    From life-calendar with MIT License 4 votes vote down vote up
export default function WeekTimeline({ data }: { data: any }) {
  const toast = useToast();
  const [mainKey, setMainKey] = React.useState(Math.random());
  const [eventModalOpen, setEventModalOpen] = React.useState(-1);
  const [state, setState] = useRecoilState<any>(appState);

  const dt = Array.from(Array(4681).keys());
  const [_data, markedWeeks] = transformData(data);

  const _todayItem = _data && _data.events.length > 0 ? _data.events[_data.events.length - 1] : { _weekNum: 2000 };
  const years = Array.from(Array(90).keys()); // [0, 1, 2, ...] as 90 years

  const renderBoxes = (yearIdx = -1) => {
    return (
      <>
        {dt.map((_, idx) => {
          if (yearIdx >= 0) {
            if (idx < yearIdx * 52.143 || idx > yearIdx * 52.143 + 52.143) {
              return null;
            }
          }
          let bgColor = '#333'; // default

          if (idx < _todayItem._weekNum) {
            bgColor = '#222'; // passed weeks
          }

          let yearTooltip = '';
          const markedWeeksIdx = markedWeeks.indexOf(idx);

          if (state.options.highlightYears) {
            // bgColor = item % 261 === 0 ? '#335' : bgColor; // highlight every year
            bgColor = markedWeeksIdx >= 0 ? '#224' : bgColor;
            yearTooltip = markedWeeksIdx >= 0 ? `${markedWeeksIdx + 1} years old` : yearTooltip;
          }

          const obj: any = _data.events.find((d: any) => d._weekNum === idx);
          if (obj) {
            bgColor = 'gray';

            if (obj.type === -3) {
              bgColor = 'darkred';
            } else if (obj.type === -2 || obj.type === -1) {
              bgColor = 'darkred';
            } else if (obj.type === 1 || obj.type === 2) {
              bgColor = '#353';
            } else if (obj.type === 3) {
              bgColor = 'pink';
            }
          }
          let boxContent = '';
          if (state.options.showEveryYears) {
            // 52.143 * 5 ~ 260.7 ~ 261
            // boxContent = '' + (item % 261 === 0 ? (item / 261) * 5 : ''); // show year number ever N years
            boxContent = '' + (markedWeeksIdx > 1 && (markedWeeksIdx + 1) % 5 === 0 ? markedWeeksIdx + 1 : '');
            yearTooltip = boxContent ? `${boxContent} years old` : yearTooltip;
          }

          // boxContent = obj ? obj.title : boxContent; // item % 52 === 0 ? item / 52 : ''
          // if first character is Emoji, show it in the box:
          boxContent = obj && obj.title && obj.title.trim().charCodeAt(0) > 255 ? [...obj.title.trim()][0] : boxContent;

          let boxStartTime = +addWeeks(_data.events[0]._date, idx);
          const boxEl = (
            <Box
              key={`box_${yearIdx}_${idx}`}
              className={css.box}
              onClick={() => setEventModalOpen(boxStartTime)}
              rounded={2}
              w={3}
              h={3}
              style={{ backgroundColor: bgColor, fontSize: 8, cursor: 'default' }}
            >
              {boxContent}
            </Box>
          );

          if ((obj && obj.title) || yearTooltip) {
            const tooltipLabel = obj && obj.title ? `${obj.date} - ${obj.title}` : yearTooltip;
            return (
              <Tooltip key={`tt_${idx}`} label={tooltipLabel}>
                {boxEl}
              </Tooltip>
            );
          } else {
            return boxEl;
          }
        })}
      </>
    );
  };
  return (
    <Flex key={mainKey} gridGap={1} width="95vw" flexWrap="wrap">
      {state.options.oneRowOneYear === true
        ? years.map((_, yearIdx) => {
            return (
              <Flex key={`flex_${yearIdx}`} gridGap={1} width="95vw" flexWrap="wrap">
                {renderBoxes(yearIdx)}
              </Flex>
            );
          })
        : renderBoxes()}

      {eventModalOpen >= 0 && (
        <EventModal
          startTime={eventModalOpen}
          isOpen={true}
          onClose={() => setEventModalOpen(-1)}
          onSubmit={(event) => {
            data.events.push(event);
            setEventModalOpen(-1);
            setMainKey(Math.random());
            toast({
              title: 'Added',
              description: `You have total ${data.events.length} events (boxes) now.`,
              status: 'success',
              duration: 9000,
              isClosable: true
            });
            localStorage.setItem('data', JSON.stringify(data));
          }}
        />
      )}
    </Flex>
  );
}