date-fns#addDays TypeScript Examples

The following examples show how to use date-fns#addDays. 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: exposure.ts    From protect-scotland with Apache License 2.0 6 votes vote down vote up
getIsolationEndDate = (
  isolationDuration: number,
  contacts?: CloseContact[],
  fmt: string = DATE_FORMAT
) => {
  const exposureDate = getExposureDate(contacts);

  if (exposureDate) {
    const isolationEndDate = addDays(exposureDate, isolationDuration);
    return {
      raw: isolationEndDate,
      formatted: format(isolationEndDate, fmt)
    };
  }
}
Example #2
Source File: Events.test.tsx    From react-calendar with MIT License 6 votes vote down vote up
test('Hides event from next week', () => {
  render(
    <WeeklyCalendarTest
      week={new Date(testDate)}
      events={[
        { title: 'Janet smith', date: subDays(new Date(testDate), 2) },
        { title: 'Max Smith', date: subDays(new Date(testDate), 1) },
        { title: 'Code', date: subHours(new Date(testDate), 4) },
        { title: 'Next week', date: addDays(new Date(testDate), 7) },
      ]}
    />
  );

  // check that all 3 are on screen
  screen.getByText('Janet smith');
  screen.getByText('Max Smith');
  screen.getByText('Code');

  screen.getByText('Mar 1st 24:00');
  expect(screen.queryByText('Next week')).toEqual(null);
});
Example #3
Source File: dummyEvents.ts    From react-calendar with MIT License 6 votes vote down vote up
events: { [key: string]: EventType[] } = {
  firstMonth: [
    { title: 'Call John', date: subHours(new Date(), 2) },
    { title: 'Call John', date: subHours(new Date(), 1) },
    { title: 'Meeting with Bob', date: new Date() },
    { title: 'Bike Appt', date: addHours(new Date(), 3) },
    { title: 'John Hilmer', date: addDays(new Date(), 3) },
    { title: 'Jane Call', date: subDays(new Date(), 4) },
    { title: 'Sound alarm', date: addDays(new Date(), 6) },
    { title: 'Soccer Practice', date: subDays(new Date(), 3) },
    { title: 'Alert', date: addHours(subDays(new Date(), 4), 4) },
    { title: 'Donation', date: addDays(new Date(), 6) },
  ],
  secondMonth: [
    { title: 'Meeting Next Month', date: addMonths(new Date(), 1) },
  ],
}
Example #4
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 #5
Source File: helper.ts    From ngx-gantt with MIT License 6 votes vote down vote up
export function randomItems(length: number, parent?: GanttItem, group?: string) {
    const items = [];
    for (let i = 0; i < length; i++) {
        const start = addDays(new Date(), random(-200, 200));
        const end = addDays(start, random(0, 100));
        items.push({
            id: `${parent?.id || group || ''}00000${i}`,
            title: `${parent?.title || 'Task'}-${i}`,
            start: getUnixTime(start),
            end: getUnixTime(end),
            group_id: group
        });
    }
    return items;
}
Example #6
Source File: calendarEvents.ts    From matx-angular with MIT License 6 votes vote down vote up
public events:  any[] = [{
    _id: '100',
    start: subDays(startOfDay(new Date()), 1),
    end: addDays(new Date(), 1),
    title: 'A 3 day event',
    color: this.colors.red
  }, {
    _id: '101',
    start: startOfDay(new Date()),
    title: 'An event with no end date',
    color: this.colors.yellow
  }, {
    _id: '102',
    start: subDays(endOfMonth(new Date()), 3),
    end: addDays(endOfMonth(new Date()), 3),
    title: 'A long event that spans 2 months',
    color: this.colors.blue
  }, {
    _id: '103',
    start: addHours(startOfDay(new Date()), 2),
    end: new Date(),
    title: 'A draggable and resizable event',
    color: this.colors.yellow,
    resizable: {
      beforeStart: true,
      afterEnd: true
    },
    draggable: true
  }];
Example #7
Source File: worklogs.ts    From tempomat with MIT License 6 votes vote down vote up
function parseWhenArg(now: Date, when: string | undefined): Date {
    if (when === undefined) return now
    if (YESTERDAY_LITERALS.includes(when)) {
        const nowAtMidnight = new Date(now)
        nowAtMidnight.setHours(0, 0, 0, 0)
        return addDays(nowAtMidnight, -1)
    }
    if (when.match(TODAY_REFERENCE_REGEX)) {
        const nowAtMidnight = new Date(now)
        nowAtMidnight.setHours(0, 0, 0, 0)
        return addDays(nowAtMidnight, parseInt(when.replace(/[^\d+-]/g, '')))
    }
    const date = fnsParse(when, DATE_FORMAT, new Date())
    if (isValid(date)) {
        return date
    } else {
        throw Error(`Cannot parse "${when}" to valid date. Try to use YYYY-MM-DD format. See ${appName} --help for more examples.`)
    }
}
Example #8
Source File: make-stat-on-interval-days-basis.ts    From merged-pr-stat with MIT License 6 votes vote down vote up
async function main(): Promise<void> {
  program
    .requiredOption("--start <date>")
    .requiredOption("--end <date>")
    .requiredOption("--interval-days <days>")
    .requiredOption("--query <query>");

  program.parse(process.argv);

  const startDate = parseISO(program.start);
  const endDate = parseISO(program.end);
  const query = program.query as string;
  const intervalDays = parseInt(program.intervalDays);

  const allStats = [];
  for (let start = startDate; start < endDate; start = addDays(start, intervalDays)) {
    const end = add(start, { days: intervalDays, seconds: -1 });
    console.error(format(start, "yyyy-MM-dd HH:mm:ss"));
    console.error(format(end, "yyyy-MM-dd HH:mm:ss"));

    const stdout = execFileSync(
      "merged-pr-stat",
      ["--start", start.toISOString(), "--end", end.toISOString(), "--query", query],
      { encoding: "utf8" }
    );
    const result = {
      startDate: format(start, "yyyy-MM-dd HH:mm:ss"),
      endDate: format(end, "yyyy-MM-dd HH:mm:ss"),
      ...JSON.parse(stdout),
    };
    allStats.push(result);
  }
  process.stdout.write(csvStringify(allStats, { header: true }));
}
Example #9
Source File: make-rotate-stat-on-interval-days-basis.ts    From merged-pr-stat with MIT License 6 votes vote down vote up
// Make stat between (<date> - <aggregationDays>) and <date>
// and move aggregation period by <intervalDays>.
async function main(): Promise<void> {
  program
    .requiredOption("--start <date>")
    .requiredOption("--end <date>")
    .requiredOption("--interval-days <days>")
    .requiredOption("--aggregation-days <days>")
    .requiredOption("--query <query>");

  program.parse(process.argv);

  const startDate = parseISO(program.start);
  const endDate = parseISO(program.end);
  const query = program.query as string;
  const intervalDays = parseInt(program.intervalDays);
  const aggregationDays = parseInt(program.aggregationDays);

  const allStats = [];
  for (let start = startDate; start < endDate; start = addDays(start, intervalDays)) {
    const aggregateFrom = add(start, { days: -aggregationDays });
    const aggregateTo = start;
    console.error(format(aggregateFrom, "yyyy-MM-dd HH:mm:ss"));
    console.error(format(aggregateTo, "yyyy-MM-dd HH:mm:ss"));

    const stdout = execFileSync(
      "merged-pr-stat",
      ["--start", aggregateFrom.toISOString(), "--end", aggregateTo.toISOString(), "--query", query],
      { encoding: "utf8" }
    );
    const result = {
      startDate: format(aggregateFrom, "yyyy-MM-dd HH:mm:ss"),
      endDate: format(aggregateTo, "yyyy-MM-dd HH:mm:ss"),
      ...JSON.parse(stdout),
    };
    allStats.push(result);
  }
  process.stdout.write(csvStringify(allStats, { header: true }));
}
Example #10
Source File: bookings.ts    From office-booker with MIT License 6 votes vote down vote up
createBooking = async (
  config: Config,
  booking: CreateBookingModel
): Promise<BookingsModel | undefined> => {
  const mapper = buildMapper(config);
  try {
    const created = await mapper.put(
      Object.assign(new BookingsModel(), booking, {
        ttl: getUnixTime(addDays(new Date(booking.date), config.dataRetentionDays)),
      }),
      {
        condition: new FunctionExpression('attribute_not_exists', new AttributePath('id')),
      }
    );
    return created;
  } catch (err) {
    if (err.code === 'ConditionalCheckFailedException') {
      return undefined;
    }
    throw err;
  }
}
Example #11
Source File: bookings.ts    From office-booker with MIT License 6 votes vote down vote up
getUserBookings = async (
  config: Config,
  userEmail: string
): Promise<BookingsModel[]> => {
  const lowerBound = subDays(new Date().getTime(), config.dataRetentionDays);
  const upperBound = addDays(new Date().getTime(), config.advanceBookingDays);

  const mapper = buildMapper(config);
  const rows: BookingsModel[] = [];
  for await (const item of mapper.query(
    BookingsModel,
    { user: userEmail },
    {
      filter: {
        type: 'Between',
        subject: 'date',
        lowerBound: format(lowerBound, 'yyyy-MM-dd'),
        upperBound: format(upperBound, 'yyyy-MM-dd'),
      },
    }
  )) {
    rows.push(item);
  }
  return rows;
}
Example #12
Source File: dates.ts    From office-booker with MIT License 6 votes vote down vote up
getVisibleDates = (
  config: Pick<Config, 'advanceBookingDays' | 'dataRetentionDays'>
) => {
  const today = new Date();
  const start = addDays(today, -1 * config.dataRetentionDays);
  return Arrays.init({ count: config.advanceBookingDays + config.dataRetentionDays }, (i) =>
    format(addDays(start, i), 'yyyy-MM-dd')
  );
}
Example #13
Source File: data.ts    From office-booker with MIT License 6 votes vote down vote up
createFakeOfficeWithSlots = (
  config: Config,
  prototype?: Partial<OfficeWithSlots>
): OfficeWithSlots => {
  return {
    ...createFakeOffice(prototype),
    slots: init(config.advancedBookingDays, (i) => ({
      date: format(addDays(new Date(), i), 'yyyy-MM-dd'),
      booked: 0,
      bookedParking: 0,
    })),
    ...prototype,
  };
}
Example #14
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 #15
Source File: coaching.ts    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
canEndCoaching = (
  startDate: string | undefined | null,
  duration: number
): boolean => {
  if (startDate) {
    return isBefore(
      addDays(startOfDay(new Date(startDate)), duration),
      startOfDay(new Date())
    )
  }

  return false
}
Example #16
Source File: MockDataUtil.ts    From legend-studio with Apache License 2.0 6 votes vote down vote up
createMockPrimitiveProperty = (
  primitiveType: PrimitiveType,
  propertyName: string,
): string | number | boolean => {
  const randomizer = new Randomizer();
  switch (primitiveType.name) {
    case PRIMITIVE_TYPE.BOOLEAN:
      return randomizer.getRandomItemInCollection([true, false]) ?? true;
    case PRIMITIVE_TYPE.FLOAT:
      return randomizer.getRandomFloat();
    case PRIMITIVE_TYPE.DECIMAL:
      return randomizer.getRandomDouble();
    case PRIMITIVE_TYPE.NUMBER:
    case PRIMITIVE_TYPE.INTEGER:
      return randomizer.getRandomWholeNumber(100);
    // NOTE that `Date` is the umbrella type that comprises `StrictDate` and `DateTime`, but for simplicity, we will generate `Date` as `StrictDate`
    case PRIMITIVE_TYPE.DATE:
    case PRIMITIVE_TYPE.STRICTDATE:
      return format(
        randomizer.getRandomDate(
          new Date(Date.now()),
          addDays(Date.now(), 100),
        ),
        DATE_FORMAT,
      );
    case PRIMITIVE_TYPE.DATETIME:
      return format(
        randomizer.getRandomDate(
          new Date(Date.now()),
          addDays(Date.now(), 100),
        ),
        DATE_TIME_FORMAT,
      );
    case PRIMITIVE_TYPE.STRING:
    default:
      return `${propertyName} ${randomizer.getRandomWholeNumber(100)}`;
  }
}
Example #17
Source File: workspace.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async resendInvitation(args: ResendInvitationArgs): Promise<Invitation> {
    const invitation = await this.prisma.invitation.findFirst({
      ...args,
      where: {
        ...args.where,
        newUser: null
      },
      include: {
        invitedByUser: {
          include: {
            account: true
          }
        }
      }
    });

    if (!invitation) {
      throw new ConflictException(`Invitation cannot be found`);
    }

    const updatedInvitation = await this.prisma.invitation.update({
      where: {
        id: invitation.id
      },
      data: {
        tokenExpiration: addDays(new Date(), INVITATION_EXPIRATION_DAYS)
      }
    });

    await this.mailService.sendInvitation({
      to: invitation.email,
      invitationToken: invitation.token,
      invitedByUserFullName: invitation.invitedByUser.account.email
    });

    return updatedInvitation;
  }
Example #18
Source File: dateFormat.ts    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
getReadHistoryDateFormat = (currentDate: Date): string => {
  const today = new Date();

  if (isDateOnlyEqual(today, currentDate)) {
    return 'Today';
  }

  if (isDateOnlyEqual(today, addDays(currentDate, 1))) {
    return 'Yesterday';
  }

  const dayOfTheWeek = format(currentDate, 'EEE');
  const dayOfTheMonth = currentDate.getDate();
  const month = format(currentDate, 'MMM');
  const currentYear = currentDate.getFullYear();
  const year = currentYear === today.getFullYear() ? '' : ` ${currentYear}`;

  return `${dayOfTheWeek}, ${dayOfTheMonth} ${month}${year}`;
}
Example #19
Source File: dateFormat.spec.ts    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
getLabel = (toCompare: Date): string => {
  const today = new Date();

  if (isDateOnlyEqual(today, toCompare)) {
    return 'Today';
  }

  if (isDateOnlyEqual(today, addDays(toCompare, 1))) {
    return 'Yesterday';
  }

  return '';
}
Example #20
Source File: QueryParametersState.ts    From legend-studio with Apache License 2.0 6 votes vote down vote up
createMockPrimitiveProperty = (
  primitiveType: PrimitiveType,
  propertyName: string,
): string | number | boolean => {
  const randomizer = new Randomizer();
  switch (primitiveType.name) {
    case PRIMITIVE_TYPE.BOOLEAN:
      return randomizer.getRandomItemInCollection([true, false]) ?? true;
    case PRIMITIVE_TYPE.FLOAT:
      return randomizer.getRandomFloat();
    case PRIMITIVE_TYPE.DECIMAL:
      return randomizer.getRandomDouble();
    case PRIMITIVE_TYPE.NUMBER:
    case PRIMITIVE_TYPE.INTEGER:
      return randomizer.getRandomWholeNumber(100);
    // NOTE that `Date` is the umbrella type that comprises `StrictDate` and `DateTime`, but for simplicity, we will generate `Date` as `StrictDate`
    case PRIMITIVE_TYPE.DATE:
    case PRIMITIVE_TYPE.STRICTDATE:
      return format(
        randomizer.getRandomDate(
          new Date(Date.now()),
          addDays(Date.now(), 100),
        ),
        DATE_FORMAT,
      );
    case PRIMITIVE_TYPE.DATETIME:
      return format(
        randomizer.getRandomDate(
          new Date(Date.now()),
          addDays(Date.now(), 100),
        ),
        DATE_TIME_FORMAT,
      );
    case PRIMITIVE_TYPE.STRING:
    default:
      return `${propertyName} ${randomizer.getRandomWholeNumber(100)}`;
  }
}
Example #21
Source File: userBookings.ts    From office-booker with MIT License 5 votes vote down vote up
incrementUserBookingCount = async (
  config: Config,
  userEmail: string,
  userQuota: number,
  weekCommencing: string
) => {
  const mapper = buildMapper(config);

  try {
    await mapper.put(
      Object.assign(new UserBookingsModel(), {
        email: userEmail,
        weekCommencing,
        bookingCount: 0,
        ttl: getUnixTime(addDays(new Date(weekCommencing), config.dataRetentionDays + 7)),
      }),
      {
        condition: {
          type: 'And',
          conditions: [
            new FunctionExpression('attribute_not_exists', new AttributePath('email')),
            new FunctionExpression('attribute_not_exists', new AttributePath('date')),
          ],
        },
      }
    );
  } catch (err) {
    if (err.code !== 'ConditionalCheckFailedException') {
      throw err;
    }
  }

  const attributes = new ExpressionAttributes();
  const updateExpression = new UpdateExpression();
  updateExpression.set(
    'bookingCount',
    new MathematicalExpression(new AttributePath('bookingCount'), '+', 1)
  );

  const quotaValue = attributes.addValue(userQuota);
  const client = new DynamoDB(config.dynamoDB);
  try {
    await client
      .updateItem({
        Key: { email: { S: userEmail }, weekCommencing: { S: weekCommencing } },
        TableName: (config.dynamoDBTablePrefix || '') + userTableName,
        UpdateExpression: updateExpression.serialize(attributes),
        ExpressionAttributeNames: attributes.names,
        ExpressionAttributeValues: attributes.values,
        ConditionExpression: `bookingCount < ${quotaValue}`,
      })
      .promise();
  } catch (err) {
    if (err.code === 'ConditionalCheckFailedException') {
      return false;
    } else {
      throw err;
    }
  }

  return true;
}
Example #22
Source File: reminder.tsx    From protect-scotland with Apache License 2.0 5 votes vote down vote up
Provider = ({children}: API) => {
  const [state, setState] = useState<State>(initialState);
  const {t} = useTranslation();
  const exposure = useExposure();

  useEffect(() => {
    const checkRunning = async () => {
      AsyncStorage.getItem(REMINDER_KEY).then((paused) => {
        setState({
          paused: paused && exposure.status.state !== StatusState.active ? paused : null,
          checked: true
        })
      });
    };

    checkRunning(); 
  }, [exposure.status.state]);

  const cancelReminder = () =>
    PushNotification.cancelLocalNotifications({id: String(REMINDER_ID)});

  const deleteReminder = () => {
    PushNotification.cancelLocalNotifications({id: String(REMINDER_ID)});
    AsyncStorage.removeItem(REMINDER_KEY);
    setState({
      ...state,
      paused: null
    });
  };

  const setReminder = (date: Date) => {
    const currentDate = new Date();
    const notificationDate = date < currentDate ? addDays(date, 1) : date;
    const timestamp = String(notificationDate.getTime());
    AsyncStorage.setItem(REMINDER_KEY, timestamp);

    PushNotification.localNotificationSchedule({
      channelId: 'default',
      id: REMINDER_ID,
      title: t('reminder:title'),
      message: t('reminder:message'),
      date: notificationDate,
      repeatType: 'hour',
      // @ts-ignore
      allowWhileIdle: true
    });

    setState({
      ...state,
      paused: timestamp
    });
  };

  const value: ReminderContextValue = {
    ...state,
    setReminder,
    deleteReminder,
    cancelReminder
  };

  return (
    <ReminderContext.Provider value={value}>
      {children}
    </ReminderContext.Provider>
  );
}
Example #23
Source File: Weekly.stories.tsx    From react-calendar with MIT License 5 votes vote down vote up
BasicWeeklyCalendar: Story = args => {
  return (
    <WeeklyResponsiveContainer>
      <WeeklyCalendar week={args.week}>
        <WeeklyContainer>
          <WeeklyDays omitDays={args.hideWeekend ? [0, 6] : undefined} />
          <WeeklyBody
            style={{ maxHeight: args.hideWeekend ? '18rem' : '26rem' }}
            events={[
              { title: 'Janet smith', date: subDays(new Date(), 3) },
              { title: 'Max Smith', date: subDays(new Date(), 1) },
              { title: 'Code', date: subHours(new Date(), 4) },
              { title: 'Call Emma', date: subHours(new Date(), 3) },
              { title: 'Eat lunch', date: subHours(new Date(), 2) },
              { title: 'Sleep', date: subHours(new Date(), 1) },
              { title: 'Meeting with Bob', date: new Date() },
              { title: 'John smith', date: addDays(new Date(), 1) },
              { title: 'Jane doe', date: addDays(new Date(), 3) },
              { title: 'Janet smith', date: subDays(new Date(), 4) },
              { title: 'Max Smith', date: subDays(new Date(), 5) },
              { title: 'John smith', date: addDays(new Date(), 4) },
              { title: 'Jane doe', date: addDays(new Date(), 5) },
            ]}
            renderItem={({ item, showingFullWeek }) => (
              <DefaultWeeklyEventItem
                key={item.date.toISOString()}
                title={item.title}
                date={
                  showingFullWeek
                    ? format(item.date, 'MMM do k:mm')
                    : format(item.date, 'k:mm')
                }
              />
            )}
          />
        </WeeklyContainer>
      </WeeklyCalendar>
    </WeeklyResponsiveContainer>
  );
}
Example #24
Source File: date.ts    From ngx-gantt with MIT License 5 votes vote down vote up
addDays(amount: number): GanttDate {
        return new GanttDate(addDays(this.value, amount));
    }
Example #25
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 #26
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 #27
Source File: ApiTokenListItem.tsx    From amplication with Apache License 2.0 5 votes vote down vote up
ApiTokenListItem = ({
  applicationId,
  apiToken,
  onDelete,
  onError,
}: Props) => {
  const expirationDate = addDays(
    new Date(apiToken.lastAccessAt),
    EXPIRATION_DAYS
  );
  const expired = differenceInDays(new Date(), expirationDate) > 0;
  const newToken = !isEmpty(apiToken.token);
  const createdDate = new Date(apiToken.createdAt);

  return (
    <Panel
      className={classNames(
        CLASS_NAME,
        {
          [`${CLASS_NAME}--expired`]: expired,
        },
        {
          [`${CLASS_NAME}--new`]: newToken,
        }
      )}
      panelStyle={EnumPanelStyle.Bordered}
    >
      <div className={`${CLASS_NAME}__panel-tag`}>
        <Icon icon="key" size="medium" />
      </div>
      <div className={`${CLASS_NAME}__panel-details`}>
        <div className={`${CLASS_NAME}__row`}>
          <h3>{apiToken.name}</h3>
          <span className="spacer" />
          <div className={`${CLASS_NAME}__created`}>
            Created <TimeSince time={createdDate} />
          </div>
          <div
            className={classNames(`${CLASS_NAME}__expiration`, {
              [`${CLASS_NAME}__expiration--expired`]: expired,
            })}
          >
            Expiration <TimeSince time={expirationDate} />
          </div>
        </div>
        {newToken && (
          <div className={`${CLASS_NAME}__row`}>{apiToken.token}</div>
        )}
        <div className={`${CLASS_NAME}__row`}>
          {!newToken && (
            <span className={`${CLASS_NAME}__token-preview`}>
              ***********{apiToken.previewChars}
            </span>
          )}
          <span className="spacer" />
          <DeleteApiToken
            apiToken={apiToken}
            onDelete={onDelete}
            onError={onError}
          />
        </div>
      </div>
    </Panel>
  );
}
Example #28
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 #29
Source File: workspace.service.ts    From amplication with Apache License 2.0 5 votes vote down vote up
async inviteUser(
    currentUser: User,
    args: InviteUserArgs
  ): Promise<Invitation | null> {
    const { workspace, id: currentUserId, account } = currentUser;

    if (isEmpty(args.data.email)) {
      throw new ConflictException(`email address is required to invite a user`);
    }

    const existingUsers = await this.userService.findUsers({
      where: {
        account: { email: args.data.email },
        workspace: { id: workspace.id }
      }
    });

    if (existingUsers.length) {
      throw new ConflictException(
        `User with email ${args.data.email} already exist in the workspace.`
      );
    }

    const existingInvitation = await this.prisma.invitation.findUnique({
      where: {
        // eslint-disable-next-line @typescript-eslint/naming-convention
        workspaceId_email: {
          email: args.data.email,
          workspaceId: workspace.id
        }
      }
    });

    if (existingInvitation) {
      throw new ConflictException(
        `Invitation with email ${args.data.email} already exist in the workspace.`
      );
    }

    const currentUserAccount = await this.prisma.account.findUnique({
      where: {
        id: account.id
      }
    });

    const invitation = await this.prisma.invitation.create({
      data: {
        email: args.data.email,
        workspace: {
          connect: {
            id: workspace.id
          }
        },
        invitedByUser: {
          connect: {
            id: currentUserId
          }
        },
        token: cuid(),
        tokenExpiration: addDays(new Date(), INVITATION_EXPIRATION_DAYS)
      }
    });

    await this.mailService.sendInvitation({
      to: invitation.email,
      invitationToken: invitation.token,
      invitedByUserFullName: currentUserAccount.email
    });

    return invitation;
  }