date-fns#getDaysInMonth TypeScript Examples

The following examples show how to use date-fns#getDaysInMonth. 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: ListProviderMonthAvailabilityService.ts    From gobarber-api with MIT License 6 votes vote down vote up
public async execute({
    provider_id,
    month,
    year,
  }: IRequest): Promise<IResponse> {
    const appointments = await this.appointmentsRepository.findAllInMonthFromProvider(
      {
        provider_id,
        month,
        year,
      },
    );

    const numberOfDaysInMonth = getDaysInMonth(new Date(year, month - 1));

    const eachDayArray = Array.from(
      { length: numberOfDaysInMonth },
      (_, index) => index + 1,
    );

    const availability = eachDayArray.map(day => {
      const compareDate = new Date(year, month - 1, day, 23, 59, 59);

      const appointmentsInDay = appointments.filter(appointment => {
        return getDate(appointment.date) === day;
      });

      return {
        day,
        available:
          isAfter(compareDate, new Date()) && appointmentsInDay.length < 10,
      };
    });

    return availability;
  }
Example #2
Source File: dateUtils.tsx    From symphony-ui-toolkit with Apache License 2.0 6 votes vote down vote up
export function getDaysNeededForNextMonth(date: Date, locale: Locale) {
  const daysNeededForLastMonth = getDaysNeededForLastMonth(date, locale);
  const lastDayOfWeek = endOfWeek(date, { locale });

  const endDate = lastDayOfMonth(date);

  // getDay return the value of the weekday from 0 to 6
  // i.e enDate is the Friday -> getDay(enDate) = 5
  // i.e. lastDayOfWeek is a Saturday -> getDay(lastDayOfWeek) = 6 (depends on locale)
  // + 7 and the modulo to ensure the result is positive value is between 0 and 6 (javascript % can return negative value)
  let daysNeededForNextMonth =
    (getDay(lastDayOfWeek) - getDay(endDate) + 7) % 7;
  if (daysNeededForLastMonth + getDaysInMonth(date) <= 35) {
    daysNeededForNextMonth += 7;
  }
  return daysNeededForNextMonth;
}
Example #3
Source File: dateUtils.tsx    From symphony-ui-toolkit with Apache License 2.0 6 votes vote down vote up
export function getBoundedDay(date: Date, nextDate: Date, locale: Locale) {
  const minBound = getDaysNeededForLastMonth(nextDate, locale);
  // if the day to focus is an "outside day", then focus the first (or last) day
  return Math.min(
    Math.max(
      minBound + 1,
      date.getDate() + getDaysNeededForLastMonth(date, locale)
    ),
    minBound + getDaysInMonth(nextDate)
  );
}
Example #4
Source File: ListProviderMonthAvailabilityService.ts    From gobarber-project with MIT License 6 votes vote down vote up
public async execute({
    provider_id,
    month,
    year,
  }: IRequest): Promise<IResponse> {
    const appointments = await this.appointmentsRepository.findAllInMonthFromProvider(
      {
        provider_id,
        month,
        year,
      },
    );

    const numberOfDaysInMonth = getDaysInMonth(new Date(year, month - 1));

    const eachDayArray = Array.from(
      { length: numberOfDaysInMonth },
      (_, index) => index + 1,
    );

    const availability = eachDayArray.map(day => {
      const compareDate = new Date(year, month - 1, day, 23, 59, 59);

      const appointmentsInDay = appointments.filter(appointment => {
        return getDate(appointment.date) === day;
      });

      return {
        day,
        available:
          isAfter(compareDate, new Date()) && appointmentsInDay.length < 10,
      };
    });

    return availability;
  }
Example #5
Source File: ListProviderMonthAvailabilityService.ts    From GoBarber with MIT License 6 votes vote down vote up
public async execute({
    provider_id,
    month,
    year,
  }: IRequest): Promise<IResponse> {
    const appointments = await this.appointmentsRepository.findAllInMonthFromProvider(
      {
        provider_id,
        month,
        year,
      },
    );

    const numberOfDaysInMonth = getDaysInMonth(new Date(year, month - 1));

    const eachDayArray = Array.from(
      { length: numberOfDaysInMonth },
      (_, index) => index + 1,
    );

    const availability = eachDayArray.map(day => {
      const compareDate = endOfDay(new Date(year, month - 1, day));

      const appointmentsInDay = appointments.filter(appointment => {
        return getDate(appointment.date) === day;
      });

      return {
        day,
        available:
          isAfter(compareDate, new Date()) && appointmentsInDay.length < 10,
      };
    });

    return availability;
  }
Example #6
Source File: ListProviderMonthAvailabilityService.ts    From hotseat-api with MIT License 5 votes vote down vote up
async execute({ provider_id, month, year }: IRequest): Promise<IResponse> {
    const provider = await this.usersRepository.findById(provider_id);

    if (!provider) {
      throw new AppError('Provider not found', 404);
    }

    const appointments = await this.appointmentsRepository.findByMonthFromProvider(
      {
        year,
        month,
        provider_id,
      },
    );

    const numberOfDaysInMonth = getDaysInMonth(month - 1);
    const daysInMonth = Array.from(
      { length: numberOfDaysInMonth },
      (_, index) => index + 1,
    );

    const availability = daysInMonth.map(day => {
      const numberOfAppointmentsInDay = appointments.filter(
        appointment => getDate(appointment.date) === day,
      ).length;

      const availabilityDate = new Date(
        year,
        parseMonthToJSMonth(month),
        day,
        23,
        59,
        59,
      );

      const isPast = isAfter(new Date(Date.now()), availabilityDate);

      return {
        day,
        isPast,
        available:
          !isPast && numberOfAppointmentsInDay < MAX_APPOINTMENTS_PER_DAY,
      };
    });

    return availability;
  }
Example #7
Source File: ngx-mat-datefns-date-adapter.ts    From ngx-mat-datefns-date-adapter with MIT License 5 votes vote down vote up
getNumDaysInMonth(date: Date): number {
    return getDaysInMonth(date);
  }
Example #8
Source File: date.ts    From ngx-gantt with MIT License 5 votes vote down vote up
getDaysInMonth() {
        return getDaysInMonth(this.value);
    }
Example #9
Source File: DayPicker.tsx    From symphony-ui-toolkit with Apache License 2.0 4 votes vote down vote up
renderBody() {
    const {
      dir,
      locale,
      selectedDays,
      disabledDays,
      highlightedDays,
      onDayClick,
    } = this.props;
    const { today, currentMonth } = this.state;
    const daysInMonth = getDaysInMonth(currentMonth);
    const daysNeededForLastMonth = getDaysNeededForLastMonth(
      currentMonth,
      locale
    );
    const daysNeededForNextMonth = getDaysNeededForNextMonth(
      currentMonth,
      locale
    );

    const selectedDateString = selectedDays
      ? lightFormat(selectedDays, 'yyyy-MM-dd')
      : null;
    const todayDateString = lightFormat(today, 'yyyy-MM-dd');

    const isSelectedDayVisible =
      selectedDays &&
      differenceInCalendarMonths(selectedDays, currentMonth) === 0;
    return (
      <div className="tk-daypicker-body" role="grid" style={{ direction: dir }}>
        {this.renderOutsideDay(daysNeededForLastMonth)}

        {toArray(daysInMonth).map((cell) => {
          const cellNumber = cell + 1;
          const cellDate = setDate(currentMonth, cellNumber);
          const cellName = formatDay(cellDate, locale);

          const itemDateString = lightFormat(cellDate, 'yyyy-MM-dd');
          const isSelected = itemDateString === selectedDateString;
          const isToday = itemDateString === todayDateString;
          const isDisabled = matchDay(cellDate, disabledDays);
          const isHighlighted = matchDay(cellDate, highlightedDays);
          const ariaSelected = isDisabled ? undefined : isSelected;
          const isTabIndex = isSelectedDayVisible
            ? isSelected
              ? 0
              : -1
            : cell === 0
              ? 0
              : -1; // focus on selected day otherwise first cell

          return (
            <div
              key={cellName}
              aria-label={cellName}
              aria-selected={ariaSelected}
              tabIndex={isTabIndex}
              role="gridcell"
              className={classNames(
                'tk-daypicker-day',
                {
                  'tk-daypicker-day--selected': isSelected,
                },
                {
                  'tk-daypicker-day--today': isToday,
                },
                {
                  'tk-daypicker-day--highlighted': isHighlighted && !isDisabled,
                },
                { 'tk-daypicker-day--disabled': isDisabled }
              )}
              onKeyDown={(e) =>
                this.handleKeyDownCell(e, cellDate, {
                  disabled: isDisabled,
                  selected: isSelected,
                })
              }
              onClick={() =>
                onDayClick(cellDate, {
                  disabled: isDisabled,
                  selected: isSelected,
                })
              }
            >
              {cellNumber}
            </div>
          );
        })}
        {this.renderOutsideDay(daysNeededForNextMonth)}
      </div>
    );
  }
Example #10
Source File: BudgetTransaction.ts    From cashcash-desktop with MIT License 4 votes vote down vote up
getters = {
    getField,
    inOutBudgetSplitObject(
        state: IBudgetTransactionState,
        getters,
        rootState,
    ): InOutBudgetSplitObject {
        const result: InOutBudgetSplitObject = {
            outBudgetSplitMap: new Map(),
            inBudgetSplitMap: new Map(),
            outBudgetSplitSum: 0,
            inBudgetSplitSum: 0,
        };
        const contextAccount = state.contextAccount;
        const budgetSplitList: GraphSplitExtended[] = rootState.PermanentData.budgetSplitList;
        const accountDescendantMap: Map<number, number[]> =
            rootState.PermanentData.accountDescendantMap;
        if (!state.isPageOpen || !contextAccount || budgetSplitList.length === 0) {
            return result;
        }
        const accountDescendantList = [
            ...(accountDescendantMap.get(contextAccount.id) || []),
            contextAccount.id,
        ];
        for (const budgetSplit of budgetSplitList) {
            if (
                accountDescendantList.includes(budgetSplit.accountId) &&
                !accountDescendantList.includes(budgetSplit.otherSplitAccountId)
            ) {
                const key = CashBudgetUtils.generateKey(budgetSplit);
                if (budgetSplit.isToSplit) {
                    // It's a in split
                    result.inBudgetSplitMap.set(key, budgetSplit);
                    result.inBudgetSplitSum += +budgetSplit.amount;
                } else {
                    // It's a out split
                    result.outBudgetSplitMap.set(key, budgetSplit);
                    result.outBudgetSplitSum += +budgetSplit.amount;
                }
            }
        }

        return result;
    },
    deltaBudgetObject(state: IBudgetTransactionState, getters): DeltaBudgetObject {
        const result: DeltaBudgetObject = {
            deltaPerMonth: 0,
            deltaPerWeek: 0,
            deltaPerDay: 0,
        };
        const budgetDate = state.budgetDate;
        const inOutBudgetSplitObject: InOutBudgetSplitObject = getters.inOutBudgetSplitObject;
        if (!state.isPageOpen || !budgetDate || !inOutBudgetSplitObject) {
            return result;
        }
        const delta =
            inOutBudgetSplitObject.inBudgetSplitSum - inOutBudgetSplitObject.outBudgetSplitSum;
        const numberOfDays = getDaysInMonth(budgetDate);
        const deltaPerDay = delta / numberOfDays;
        return {
            deltaPerMonth: delta,
            deltaPerWeek: deltaPerDay * 7,
            deltaPerDay,
        };
    },
    inOutCurrentSplitObject(
        state: IBudgetTransactionState,
        getters,
        rootState,
    ): InOutCurrentSplitObject {
        const result: InOutCurrentSplitObject = {
            outCurrentSplitList: [],
            inCurrentSplitList: [],
            outCurrentSplitSum: 0,
            inCurrentSplitSum: 0,
            outBudgetedCurrentSumMap: new Map(),
            inBudgetedCurrentSumMap: new Map(),
            currentSumMap: new Map(),
            outBudgetedCurrentSplitSum: 0,
            inBudgetedCurrentSplitSum: 0,
            outNoneBudgetedCurrentSplitList: [],
            inNoneBudgetedCurrentSplitList: [],
            outNoneBudgetedCurrentSplitSum: 0,
            inNoneBudgetedCurrentSplitSum: 0,
        };
        const inOutBudgetSplitObject: InOutBudgetSplitObject = getters.inOutBudgetSplitObject;
        const contextAccount = state.contextAccount;
        const splitList: GraphSplitExtended[] = rootState.TimeFrameData.splitList;
        const budgetDate = state.budgetDate;
        const accountDescendantMap: Map<number, number[]> =
            rootState.PermanentData.accountDescendantMap;
        if (
            !state.isPageOpen ||
            !inOutBudgetSplitObject ||
            !contextAccount ||
            splitList.length === 0 ||
            !budgetDate
        ) {
            return result;
        }
        const accountDescendantList = [
            ...(accountDescendantMap.get(contextAccount.id) || []),
            contextAccount.id,
        ];
        for (const split of splitList) {
            if (
                isSameMonth(split.transactionDate, budgetDate) &&
                accountDescendantList.includes(split.accountId) &&
                !accountDescendantList.includes(split.otherSplitAccountId)
            ) {
                const key = CashBudgetUtils.generateKey(split);
                if (split.isToSplit) {
                    // It's a in split
                    if (inOutBudgetSplitObject.inBudgetSplitMap.get(key)) {
                        // It's part of a budgeted account
                        let oneSum = result.inBudgetedCurrentSumMap.get(key) || 0;
                        oneSum += split.amount;
                        result.inBudgetedCurrentSumMap.set(key, oneSum);
                        result.currentSumMap.set(key, oneSum);
                        result.inBudgetedCurrentSplitSum += split.amount;
                    } else {
                        result.inNoneBudgetedCurrentSplitList.push(split);
                        result.inNoneBudgetedCurrentSplitSum += split.amount;
                    }
                    result.inCurrentSplitList.push(split);
                    result.inCurrentSplitSum += split.amount;
                } else {
                    // It's a out split
                    if (inOutBudgetSplitObject.outBudgetSplitMap.get(key)) {
                        // It's part of a budgeted account
                        let oneSum = result.outBudgetedCurrentSumMap.get(key) || 0;
                        oneSum += split.amount;
                        result.outBudgetedCurrentSumMap.set(key, oneSum);
                        result.currentSumMap.set(key, oneSum);
                        result.outBudgetedCurrentSplitSum += split.amount;
                    } else {
                        result.outNoneBudgetedCurrentSplitList.push(split);
                        result.outNoneBudgetedCurrentSplitSum += split.amount;
                    }
                    result.outCurrentSplitList.push(split);
                    result.outCurrentSplitSum += split.amount;
                }
            }
        }
        return result;
    },
    deltaCurrentObject(state: IBudgetTransactionState, getters): DeltaCurrentObject {
        const result: DeltaCurrentObject = {
            deltaPerMonth: 0,
            deltaPerWeek: 0,
            deltaPerDay: 0,
        };
        const budgetDate = state.budgetDate;
        const inOutCurrentSplitObject: InOutCurrentSplitObject = getters.inOutCurrentSplitObject;
        if (!state.isPageOpen || !budgetDate || !inOutCurrentSplitObject) {
            return result;
        }
        const delta = inOutCurrentSplitObject.outNoneBudgetedCurrentSplitSum;
        const numberOfDays = getDaysInMonth(budgetDate);
        const deltaPerDay = delta / numberOfDays;
        return {
            deltaPerMonth: delta,
            deltaPerWeek: deltaPerDay * 7,
            deltaPerDay,
        };
    },
    optionChart(state: IBudgetTransactionState, getters, rootState, rootGetters) {
        const inOutCurrentSplitObject: InOutCurrentSplitObject = getters.inOutCurrentSplitObject;
        const inOutBudgetSplitObject: InOutBudgetSplitObject = getters.inOutBudgetSplitObject;
        const preferedCurrency = rootState.App.preferences
            ? rootState.App.preferences.preferedCurrency
            : null;
        const accountMap = rootState.PermanentData.accountMap;
        const currencyMap = rootGetters['PermanentData/currencyMap'];
        const service = Container.get(CashGraphService);
        if (
            !state.isPageOpen ||
            !inOutBudgetSplitObject ||
            !inOutBudgetSplitObject ||
            !preferedCurrency ||
            !accountMap ||
            !currencyMap
        ) {
            return {};
        }
        return service.generateBudgetGraph(
            inOutBudgetSplitObject.inBudgetSplitSum,
            -inOutBudgetSplitObject.outBudgetSplitSum,
            inOutCurrentSplitObject.inBudgetedCurrentSplitSum,
            -inOutCurrentSplitObject.outBudgetedCurrentSplitSum,
            inOutCurrentSplitObject.inNoneBudgetedCurrentSplitSum,
            -inOutCurrentSplitObject.outNoneBudgetedCurrentSplitSum,
            state.budgetDate,
            preferedCurrency,
            accountMap,
            currencyMap,
        );
    },
}