date-fns#startOfDay TypeScript Examples

The following examples show how to use date-fns#startOfDay. 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: RelativeRangeBody.tsx    From gio-design with Apache License 2.0 6 votes vote down vote up
function RelativeRangeBody({ dateRange, fixedMode, onRangeChange, disabledDate }: RelativeRangeBodyProps) {
  if (fixedMode) {
    const handleOnSelect = (current: Date) => {
      onRangeChange([startOfDay(current), startOfYesterday()]);
    };
    return <DatePicker disabledDate={disabledDate} value={dateRange[0]} onSelect={handleOnSelect} />;
  }
  return <DateRangePicker disabledDate={disabledDate} onSelect={onRangeChange} value={dateRange as [Date, Date]} />;
}
Example #2
Source File: habit-actions.ts    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
markTodayHabitAsCompleted = (habit: Habit): AppThunk => async (
  dispatch
) => {
  const today = startOfDay(new Date()).toISOString()
  const { days, longestDayStreak = 0 } = habit
  let { dayStreak = 0 } = habit
  let dayValue = 0

  if (days.has(today)) {
    const completedToday = days.get(today) === 1

    if (!completedToday) {
      dayStreak += 1
      dayValue = 1
    } else {
      dayStreak -= 1
      dayValue = 0
    }
  } else {
    dayStreak += 1
    dayValue = 1
  }

  const updatedDays = produce(days, (draft) => {
    draft.set(today, dayValue)
  })

  const updatedHabit: Habit = {
    ...habit,
    days: updatedDays,
    latestCompletedDate: today,
    dayStreak,
    longestDayStreak:
      longestDayStreak > dayStreak ? longestDayStreak : dayStreak
  }
  await dispatch(updateEditedHabit(updatedHabit))
  await dispatch(stashHabitToSync(updatedHabit, MutationType.UPDATE))
}
Example #3
Source File: nights.ts    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
getNightsAsDays = createSelector(getNights, (nights) => {
  const days = eachDayOfInterval({
    start: subDays(new Date(), 30),
    end: new Date() // lastDate
  })

  return days.map((day) => ({
    date: day.toISOString(),
    inBedDuration: 0,
    asleepDuration: 0,
    night: nights
      .filter((night) => matchDayAndNight(night.startDate, day.toISOString()))
      .map((night) => {
        const startDifference = differenceInMilliseconds(
          new Date(night.startDate),
          startOfDay(new Date(day))
        )

        const newStartDate = addMilliseconds(
          startOfDay(new Date()),
          startDifference
        )

        const newEndDate = addMinutes(newStartDate, night.totalDuration)

        return {
          ...night,
          startDate: newStartDate.valueOf(),
          endDate: newEndDate.valueOf()
        }
      })
  }))
})
Example #4
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 #5
Source File: habit-actions.ts    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
addHabit = (
  title: string,
  description = '',
  period: Period,
  id?: string
): AppThunk => async (dispatch) => {
  const days = new Map()

  const habit: Habit = {
    id: id || v4(),
    userId: null,
    title: title.trim(),
    description: convertLineBreaks(description.trim()),
    days,
    date: startOfDay(new Date()).toISOString(),
    period
  }

  await dispatch(updateEditedHabit(habit))
  await dispatch(stashHabitToSync(habit, MutationType.CREATE))
}
Example #6
Source File: SleepChart.tsx    From nyxo-website with MIT License 6 votes vote down vote up
getNightAsDays = (nights: Night[]) => {
  const firstDate = min([...nights.map((night) => new Date(night.startDate))])
  const lastDate = max([...nights.map((night) => new Date(night.endDate))])

  const days = eachDayOfInterval({
    start: subDays(new Date(), 30),
    end: new Date(), // lastDate
  })

  return days.map((day) => ({
    date: day.toISOString(),
    night: nights
      .filter((night) => matchDayAndNight(night.startDate, day.toISOString()))
      .map((night) => {
        const startDifference = differenceInMilliseconds(
          new Date(night.startDate),
          startOfDay(new Date(day))
        )

        const newStartDate = addMilliseconds(
          startOfDay(new Date()),
          startDifference
        )

        const newEndDate = addMinutes(newStartDate, night.totalDuration)

        return {
          ...night,
          startDate: newStartDate.valueOf(),
          endDate: newEndDate.valueOf(),
        }
      }),
  }))
}
Example #7
Source File: sleep-data-helper.ts    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
export function calculateSocialJetlag(
  lastSevenDays: Day[]
): {
  weekDayAverage: string
  weekendDayAverage: string
} {
  const weekdays = lastSevenDays.filter(
    (day: Day) => !isWeekend(new Date(day.date))
  )
  const weekendDays = lastSevenDays.filter((day: Day) =>
    isWeekend(new Date(day.date))
  )

  const weekDayAverage = setMinutes(
    startOfDay(new Date()),
    getAverageOfTimes(weekdays)
  ).toISOString()
  const weekendDayAverage = setMinutes(
    startOfDay(new Date()),
    getAverageOfTimes(weekendDays)
  ).toISOString()

  const insights = {
    weekDayAverage,
    weekendDayAverage
  }

  return insights
}
Example #8
Source File: RelativeRangePicker.tsx    From gio-design with Apache License 2.0 6 votes vote down vote up
function RelativeRangePicker({ disabledDate, timeRange, onSelect, onCancel, ...rest }: RangePickerProps) {
  const defaultDates = parseStartAndEndDate(timeRange ?? 'day:2,1');
  const [dates, setDates] = React.useState<[Date, Date]>(defaultDates as [Date, Date]);
  const [endDateHidden, setEndDateHidden] = React.useState<boolean>(isYesterday(dates[1]));
  const inputDisabled = !isNil(disabledDate);
  const handleDisabledDate = (current: Date) =>
    disabledDate?.(current) || isAfter(startOfDay(current), endDateHidden ? startOfYesterday() : startOfToday());
  const handleOnOK = () => {
    onSelect(`day:${differenceInDays(startOfToday(), dates[0]) + 1},${differenceInDays(startOfToday(), dates[1])}`);
  };
  return (
    <InnerRangePanel
      data-testid="relative-range-picker"
      disableOK={!isValid(dates[0]) || !isValid(dates[1])}
      header={<RelativeRangeHeader inputDisabled={inputDisabled} dateRange={dates} onRangeChange={setDates} onModeChange={setEndDateHidden} />}
      body={
        <RelativeRangeBody
          dateRange={dates}
          fixedMode={endDateHidden}
          disabledDate={handleDisabledDate}
          onRangeChange={setDates}
        />
      }
      onCancel={onCancel}
      onOK={handleOnOK}
      {...rest}
    />
  );
}
Example #9
Source File: calendar.tsx    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
useCalendar = (): Calendar => {
  const dispatch = useAppDispatch()
  const selectedDate = useAppSelector((state) => state.calendar.selectedDay)

  const selectDate = (date: Date) => {
    dispatch(setSelectedDay(startOfDay(date).toISOString()))
  }

  return {
    selectDate,
    selectedDate
  }
}
Example #10
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 #11
Source File: utils.tsx    From gio-design with Apache License 2.0 6 votes vote down vote up
getDefaultViewDates = (defaultDate: Date) =>
  [startOfDay(defaultDate), add(startOfDay(defaultDate), { months: 1 })] as [Date, Date]
Example #12
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 #13
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 #14
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 #15
Source File: TimeFrameData.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
state: ITimeFrameDataState = {
    parameters: {
        accountIdList: [],
        fromAccountIdList: [],
        toAccountIdList: [],
        currencyIdList: [],
        transactionTypeList: [],
        accountTypeList: [],
        tagIdList: [],
        createdDateFrom: undefined,
        createdDateTo: undefined,
        updatedDateFrom: undefined,
        updatedDateTo: undefined,
        transactionDateFrom: startOfDay(addMonths(DateUtils.newDate(), -6)),
        transactionDateTo: endOfDay(DateUtils.newDate()),
        searchString: undefined,
        detailSearchString: undefined,
        amountLessThan: undefined,
        amountGreaterThan: undefined,
    },

    splitList: [],
    splitSumList: [],
    activeAccountIdSet: new Set(),
    splitListValid: false,
    splitSumListValid: false,
}
Example #16
Source File: event.model.ts    From matx-angular with MIT License 6 votes vote down vote up
constructor(data?) {
    data = data || {};
    this.start = new Date(data.start) || startOfDay(new Date());
    this.end = data.end ? new Date(data.end) : null;
    this._id = data._id || '';
    this.title = data.title || '';
    this.color = {
      primary: data.color && data.color.primary || '#247ba0',
      secondary: data.color && data.color.secondary || '#D1E8FF'
    };
    this.draggable = data.draggable || true;
    this.resizable = {
      beforeStart: data.resizable && data.resizable.beforeStart || true,
      afterEnd: data.resizable && data.resizable.afterEnd || true
    };
    this.actions = data.actions || [];
    this.allDay = data.allDay || false;
    this.cssClass = data.cssClass || '';
    this.meta = {
      location: data.meta && data.meta.location || '',
      notes: data.meta && data.meta.notes || ''
    };
  }
Example #17
Source File: time.ts    From nyxo-app with GNU General Public License v3.0 5 votes vote down vote up
export function toNightTime(date: string): string {
  const nightEnd = new Date(date)
  const nightStart = startOfDay(subDays(new Date(nightEnd), 1))
  return `${format(nightStart, 'dd.MM.')}${format(nightStart, 'dd.MM.')}`
}
Example #18
Source File: date.ts    From ngx-gantt with MIT License 5 votes vote down vote up
startOfDay(): GanttDate {
        return new GanttDate(startOfDay(this.value));
    }
Example #19
Source File: SleepChart.tsx    From nyxo-website with MIT License 5 votes vote down vote up
export function matchDayAndNight(night: string, day: string): boolean {
  const nightTime = new Date(night)
  const nightStart = subHours(startOfDay(new Date(day)), 12)
  const nightEnd = addHours(startOfDay(new Date(day)), 12)

  return isWithinInterval(nightTime, { start: nightStart, end: nightEnd })
}
Example #20
Source File: tools.ts    From ng-ant-admin with MIT License 5 votes vote down vote up
fnStartOfDay = function StartOfDay(time: number) {
  return startOfDay(time).getTime();
}
Example #21
Source File: service.ts    From expresso with MIT License 5 votes vote down vote up
/**
   * Send Notification
   */
  public static async sendNotification(): Promise<void> {
    const getNotification = await Notification.findOne({
      where: {
        isRead: false,
        isSend: false,
        sendAt: {
          [Op.and]: [
            { [Op.gte]: startOfDay(new Date()) },
            { [Op.lt]: new Date() },
          ],
        },
      },
    })

    if (getNotification) {
      // update notification
      await getNotification.update({ isSend: true })

      // check user id = null ( if user id null = send all notif to all user )
      if (_.isEmpty(getNotification.UserId)) {
        // FCM Token from get All
        const limitPushNotif = 200
        const getFcmToken = await FcmTokenService.getToken()

        // loop array chunk
        if (!_.isEmpty(getFcmToken)) {
          const newArrayToken = _.chunk(getFcmToken, limitPushNotif)

          // limit send notif to 100 user
          for (let i = 0; i < newArrayToken.length; i += 1) {
            const itemToken = newArrayToken[i]

            // check token fcm != null
            if (!_.isEmpty(itemToken)) {
              const dataFCM = await FCMHelper.sendMulticast({
                deviceTokens: itemToken,
                title: getNotification?.title,
                message: getNotification?.text,
                type: getNotification?.type,
                data: JSON.stringify(getNotification),
              })

              console.log(chalk.cyan('sending all notification...'), dataFCM)
            }
          }
        }
      } else {
        // get fcm token by user
        const getFcmToken = await FcmTokenService.findByUser(
          String(getNotification.UserId),
          { lang: 'en' }
        )

        // check token fcm != null
        if (!_.isEmpty(getFcmToken.token)) {
          const dataFCM = await FCMHelper.sendToDevice({
            deviceTokens: [getFcmToken.token],
            title: getNotification.title,
            message: getNotification.text,
            type: getNotification.type,
            data: JSON.stringify(getNotification),
          })

          console.log(
            chalk.cyan('sending to user notification...'),
            dataFCM.results
          )
        }
      }
    }
  }
Example #22
Source File: gmt9am.ts    From anchor-web-app with Apache License 2.0 5 votes vote down vote up
export function gmt9am(timestamp: number) {
  return addHours(
    subMinutes(startOfDay(timestamp), new Date().getTimezoneOffset()),
    9,
  ).getTime();
}
Example #23
Source File: sleep.ts    From nyxo-app with GNU General Public License v3.0 5 votes vote down vote up
getStartEndDay = (): StartEnd => {
  return {
    startDate: startOfDay(new Date()).toISOString(),
    endDate: endOfDay(new Date()).toISOString()
  }
}
Example #24
Source File: sleep.ts    From nyxo-app with GNU General Public License v3.0 5 votes vote down vote up
getStartEndWeek = (): StartEnd => {
  return {
    startDate: startOfDay(subDays(new Date(), 7)).toISOString(),
    endDate: endOfDay(new Date()).toISOString()
  }
}
Example #25
Source File: sleep-data-helper.ts    From nyxo-app with GNU General Public License v3.0 5 votes vote down vote up
// Used to match sleep samples to date
export function matchDayAndNight(night: string, day: string): boolean {
  const nightTime = new Date(night)
  const nightStart = subHours(startOfDay(new Date(day)), 12)
  const nightEnd = addHours(startOfDay(new Date(day)), 12)
  return isWithinInterval(nightTime, { start: nightStart, end: nightEnd })
}
Example #26
Source File: sleep-data-helper.ts    From nyxo-app with GNU General Public License v3.0 5 votes vote down vote up
export function calculateBedtimeWindow(
  lastSevenDays: Day[]
): {
  goToSleepWindowStart: string
  goToSleepWindowCenter: string
  goToSleepWindowEnd: string
} {
  let averageBedTime = 0
  let divideBy = 0
  lastSevenDays.forEach((day) => {
    const dayStarted = new Date(day.date) // Beginning of the day
    if (day.bedStart) {
      const bedTimeStart = new Date(day.bedStart)

      const totalDifference = differenceInMinutes(bedTimeStart, dayStarted)
      // Add difference to the average time
      averageBedTime += totalDifference
      // increment divider
      divideBy += 1
    }
  })

  if (divideBy !== 0) {
    averageBedTime /= divideBy
  }

  // Remove the extra 24 hours
  if (averageBedTime > 1440) {
    averageBedTime = -1440
  }

  const bedTimeWindowCenter = roundToNearestMinutes(
    setMinutes(startOfDay(new Date()), averageBedTime),
    {
      nearestTo: 15
    }
  ).toISOString()

  const bedTimeWindowStart = subMinutes(
    new Date(bedTimeWindowCenter),
    45
  ).toISOString()

  const bedTimeWindowEnd = addMinutes(
    new Date(bedTimeWindowCenter),
    45
  ).toISOString()

  const insights = {
    goToSleepWindowStart: bedTimeWindowStart,
    goToSleepWindowCenter: bedTimeWindowCenter,
    goToSleepWindowEnd: bedTimeWindowEnd
  }

  return insights
}
Example #27
Source File: habits.ts    From nyxo-app with GNU General Public License v3.0 5 votes vote down vote up
shouldResetDayStreak = ({
  latestCompletedDate
}: Habit): boolean => {
  const today = startOfDay(new Date())
  const lastDate = new Date(latestCompletedDate ?? new Date())
  return !isSameDay(today, lastDate)
}
Example #28
Source File: habits.ts    From nyxo-app with GNU General Public License v3.0 5 votes vote down vote up
isCompletedToday = (habit: Habit): boolean => {
  const today = startOfDay(new Date()).toISOString()
  return !!(habit?.days.has(today) && habit?.days.get(today) === 1)
}
Example #29
Source File: CalendarModal.tsx    From nyxo-app with GNU General Public License v3.0 5 votes vote down vote up
CalendarModal: FC = () => {
  const isVisible = useAppSelector(({ modal }) => modal.calendar)
  const dispatch = useAppDispatch()
  const { selectedDate, selectDate } = useCalendar()

  const onDayPress: DateCallbackHandler = async ({ timestamp }) => {
    selectDate(new Date(timestamp))
    const startDate = startOfDay(subDays(timestamp, 1)).toISOString()
    const endDate = endOfDay(timestamp).toISOString()
    // dispatch(fetchSle(startDate, endDate)) FIXME
  }

  const toggleModal = () => {
    dispatch(toggleCalendarModal(true))
  }

  const { markedDates } = useMemo(
    () => ({
      markedDates: {
        [format(new Date(selectedDate), 'yyyy-MM-dd')]: {
          selected: true
        }
      }
    }),
    [selectedDate]
  )

  const getMonthData: DateCallbackHandler = ({ month, year }) => {
    dispatch()
    // fetchSleepData(
    //   new Date(year, month - 1, 1).toISOString(),
    //   new Date(year, month - 1, 0).toISOString()
    // ) FIXME
  }

  return (
    <StyledModal
      backdropTransitionOutTiming={0}
      hideModalContentWhileAnimating
      isVisible={isVisible}
      useNativeDriver={false}
      onBackdropPress={toggleModal}>
      <Container>
        <ThemedCalendar
          onMonthChange={getMonthData}
          hideExtraDays
          minDate={minDate}
          markedDates={markedDates}
          showWeekNumbers
          maxDate={new Date()}
          enableSwipeMonths
          onDayPress={onDayPress}
        />
      </Container>
    </StyledModal>
  )
}