date-fns#startOfDay JavaScript 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: utils.js    From react-nice-dates with MIT License 6 votes vote down vote up
isSelectable = (date, { minimumDate, maximumDate }) =>
  !isBefore(date, startOfDay(minimumDate)) && !isAfter(date, maximumDate)
Example #2
Source File: utils.js    From react-nice-dates with MIT License 6 votes vote down vote up
isRangeLengthValid = ({ startDate, endDate }, { minimumLength, maximumLength }) =>
  differenceInDays(startOfDay(endDate), startOfDay(startDate)) >= minimumLength &&
  (!maximumLength || differenceInDays(startOfDay(endDate), startOfDay(startDate)) <= maximumLength)
Example #3
Source File: DateRangePicker.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
DateRangePicker = ({ timelineProps, dateRangeFilter, updateDateRangeFilter }) => {
  const { minimumDate, maximumDate } = timelineProps;
  if (!minimumDate || !maximumDate) {
    return null;
  }

  const { dateRangeStart = minimumDate, dateRangeEnd = maximumDate } = dateRangeFilter;

  return (
    <View style={styles.container}>
      <DatePicker
        activeDate={dateRangeStart}
        minimumDate={minimumDate}
        maximumDate={min([maximumDate, dateRangeEnd])}
        onDateSelect={(d) => updateDateRangeFilter('dateRangeStart', startOfDay(d))}
      />
      <View><Text style={styles.dash}>-</Text></View>
      <DatePicker
        activeDate={dateRangeEnd}
        minimumDate={max([minimumDate, dateRangeStart])}
        maximumDate={maximumDate}
        onDateSelect={(d) => updateDateRangeFilter('dateRangeEnd', endOfDay(d))}
      />
    </View>
  );
}
Example #4
Source File: index.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
dateRangeForAllRecordsSelector = createSelector(
  [allValidRecordsSortedByDateSelector],
  (items) => {
    const r1 = items[0]; // might be same as r2
    const r2 = items[items.length - 1];
    return ({
      minimumDate: r1 && startOfDay(r1.timelineDate),
      maximumDate: r2 && endOfDay(r2.timelineDate),
    });
  },
)
Example #5
Source File: index.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
timelinePropsSelector = createSelector(
  [recordsFilteredByAllButDateSelector],
  (items) => {
    const r1 = items[0]; // might be same as r2
    const r2 = items[items.length - 1];
    return ({
      minimumDate: r1 && startOfDay(r1.timelineDate),
      maximumDate: r2 && endOfDay(r2.timelineDate),
    });
  },
)
Example #6
Source File: timeline-intervals.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
createIntervalMap = (minDate, maxDate, intervalCount) => {
  const intervalMap = [];
  const startTime = minDate.getTime();
  const totalInterval = maxDate.getTime() - startTime;
  const intervalLength = totalInterval / intervalCount;
  const intervalWidth = (1 / intervalCount);
  for (let i = 0; i < intervalCount; i += 1) {
    const intervalStart = startTime + (i * intervalLength);
    intervalMap[i] = {
      key: `interval-${i}`,
      index: i,
      items: [],
      markedItems: [],
      position: (i * intervalWidth + intervalWidth / 2), // a number from 0..1
      interval: {
        start: startOfDay(new Date(intervalStart)),
        end: endOfDay(new Date(intervalStart + intervalLength)), // intervals will overlap
      },
    };
  }
  return intervalMap;
}
Example #7
Source File: date.js    From umami with MIT License 6 votes vote down vote up
export function getDateRangeValues(startDate, endDate) {
  let unit = 'year';
  if (differenceInHours(endDate, startDate) <= 48) {
    unit = 'hour';
  } else if (differenceInCalendarDays(endDate, startDate) <= 90) {
    unit = 'day';
  } else if (differenceInCalendarMonths(endDate, startDate) <= 24) {
    unit = 'month';
  }

  return { startDate: startOfDay(startDate), endDate: endOfDay(endDate), unit };
}
Example #8
Source File: DeliveryDashboardController.js    From FastFeet with MIT License 5 votes vote down vote up
async update(req, res) {
    const { id: deliveryman_id, deliveryId } = req.params;

    const deliveryman = await Deliveryman.findOne({
      where: { id: deliveryman_id }
    });

    if (!deliveryman) {
      return res.status(400).json({ error: 'Deliveryman does not exists' });
    }

    const initialDate = new Date();
    const initialHour = setSeconds(setMinutes(setHours(initialDate, 8), 0), 0);
    const finalHour = setSeconds(setMinutes(setHours(initialDate, 18), 0), 0);

    if (isAfter(initialDate, finalHour) || isBefore(initialDate, initialHour)) {
      return res
        .status(400)
        .json({ error: 'Orders pickup only between 08:00AM and 18:00PM' });
    }

    const { count: numbersOfDeliveries } = await Delivery.findAndCountAll({
      where: {
        deliveryman_id,
        start_date: {
          [Op.between]: [startOfDay(initialDate), endOfDay(initialDate)]
        }
      }
    });

    if (numbersOfDeliveries >= 5) {
      return res.status(400).json({ error: 'Maximum deliveries reached' });
    }

    const UpdatedDelivery = await Delivery.findOne({
      where: {
        id: deliveryId,
        deliveryman_id
      }
    });

    if (!UpdatedDelivery)
      res.status(400).json({ error: 'Delivery does not exists' });

    await UpdatedDelivery.update({
      start_date: initialDate
    });

    return res.status(200).json(UpdatedDelivery);
  }
Example #9
Source File: common-functions.js    From covid19Nepal-react with MIT License 5 votes vote down vote up
getNepalDay = () => {
  return startOfDay(utcToZonedTime(new Date(), 'Asia/Kathmandu'));
}
Example #10
Source File: date.js    From umami with MIT License 5 votes vote down vote up
export function getDateRange(value, locale = 'en-US') {
  const now = new Date();
  const dateLocale = getDateLocale(locale);

  const match = value.match(/^(?<num>[0-9]+)(?<unit>hour|day|week|month|year)$/);

  if (!match) return;

  const { num, unit } = match.groups;

  if (+num === 1) {
    switch (unit) {
      case 'day':
        return {
          startDate: startOfDay(now),
          endDate: endOfDay(now),
          unit: 'hour',
          value,
        };
      case 'week':
        return {
          startDate: startOfWeek(now, { locale: dateLocale }),
          endDate: endOfWeek(now, { locale: dateLocale }),
          unit: 'day',
          value,
        };
      case 'month':
        return {
          startDate: startOfMonth(now),
          endDate: endOfMonth(now),
          unit: 'day',
          value,
        };
      case 'year':
        return {
          startDate: startOfYear(now),
          endDate: endOfYear(now),
          unit: 'month',
          value,
        };
    }
  }

  switch (unit) {
    case 'day':
      return {
        startDate: subDays(startOfDay(now), num - 1),
        endDate: endOfDay(now),
        unit,
        value,
      };
    case 'hour':
      return {
        startDate: subHours(startOfHour(now), num - 1),
        endDate: endOfHour(now),
        unit,
        value,
      };
  }
}
Example #11
Source File: date.js    From umami with MIT License 5 votes vote down vote up
dateFuncs = {
  minute: [differenceInMinutes, addMinutes, startOfMinute],
  hour: [differenceInHours, addHours, startOfHour],
  day: [differenceInCalendarDays, addDays, startOfDay],
  month: [differenceInCalendarMonths, addMonths, startOfMonth],
  year: [differenceInCalendarYears, addYears, startOfYear],
}
Example #12
Source File: DateRangePickerCalendar.js    From react-nice-dates with MIT License 4 votes vote down vote up
export default function DateRangePickerCalendar({
  locale,
  startDate,
  endDate,
  focus,
  month: receivedMonth,
  onStartDateChange,
  onEndDateChange,
  onFocusChange,
  onMonthChange,
  minimumDate,
  maximumDate,
  minimumLength,
  maximumLength,
  modifiers: receivedModifiers,
  modifiersClassNames,
  weekdayFormat,
  touchDragEnabled
}) {
  const [hoveredDate, setHoveredDate] = useState()
  const [month, setMonth] = useControllableState(
    receivedMonth,
    onMonthChange,
    startOfMonth(startDate || endDate || new Date())
  )

  const displayedStartDate =
    focus === START_DATE && !startDate && endDate && hoveredDate && !isSameDay(hoveredDate, endDate)
      ? hoveredDate
      : startOfDay(startDate)

  const displayedEndDate =
    focus === END_DATE && !endDate && startDate && hoveredDate && !isSameDay(hoveredDate, startDate)
      ? hoveredDate
      : startOfDay(endDate)

  const isStartDate = date => isSameDay(date, displayedStartDate) && isBefore(date, displayedEndDate)
  const isMiddleDate = date => isAfter(date, displayedStartDate) && isBefore(date, displayedEndDate)
  const isEndDate = date => isSameDay(date, displayedEndDate) && isAfter(date, displayedStartDate)

  const modifiers = mergeModifiers(
    {
      selected: date =>
        isSelectable(date, { minimumDate, maximumDate }) &&
        (isStartDate(date) ||
          isMiddleDate(date) ||
          isEndDate(date) ||
          isSameDay(date, startDate) ||
          isSameDay(date, endDate)),
      selectedStart: isStartDate,
      selectedMiddle: isMiddleDate,
      selectedEnd: isEndDate,
      disabled: date =>
        (focus === START_DATE &&
          endDate &&
          ((differenceInDays(startOfDay(endDate), date) < minimumLength && (!startDate || !isAfter(date, startOfDay(endDate)))) ||
            (!startDate && maximumLength && differenceInDays(startOfDay(endDate), date) > maximumLength))) ||
        (focus === END_DATE &&
          startDate &&
          ((differenceInDays(date, startOfDay(startDate)) < minimumLength && (!endDate || !isBefore(date, startOfDay(startDate)))) ||
            (!endDate && maximumLength && differenceInDays(date, startOfDay(startDate)) > maximumLength)))
    },
    receivedModifiers
  )

  const handleSelectDate = date => {
    if (focus === START_DATE) {
      const invalidEndDate =
        endDate && !isRangeLengthValid({ startDate: date, endDate }, { minimumLength, maximumLength })

      if (invalidEndDate) {
        onEndDateChange(null)
      }

      onStartDateChange(startDate ? setTime(date, startDate) : date)
      onFocusChange(END_DATE)
    } else if (focus === END_DATE) {
      const invalidStartDate =
        startDate && !isRangeLengthValid({ startDate, endDate: date }, { minimumLength, maximumLength })

      if (invalidStartDate) {
        onStartDateChange(null)
      }

      onEndDateChange(endDate ? setTime(date, endDate) : date)
      onFocusChange(invalidStartDate || !startDate ? START_DATE : null)
    }
  }

  return (
    <Calendar
      locale={locale}
      month={month}
      onMonthChange={setMonth}
      onDayHover={setHoveredDate}
      onDayClick={handleSelectDate}
      minimumDate={minimumDate}
      maximumDate={maximumDate}
      modifiers={modifiers}
      modifiersClassNames={modifiersClassNames}
      weekdayFormat={weekdayFormat}
      touchDragEnabled={touchDragEnabled}
    />
  )
}
Example #13
Source File: DateRangePickerCalendar.test.js    From react-nice-dates with MIT License 4 votes vote down vote up
describe('DateRangePickerCalendar', () => {
  it('should render', () => {
    const { getAllByText } = render(
      <DateRangePickerCalendar
        locale={locale}
        onStartDateChange={() => {}}
        onEndDateChange={() => {}}
        onFocusChange={() => {}}
      />
    )

    expect(getAllByText('1').length).toBeGreaterThan(0)
  })

  it('should call callbacks on date selection', () => {
    const handleStartDateChange = jest.fn()
    const handleEndDateChange = jest.fn()
    const handleFocusChange = jest.fn()

    const { getAllByText, rerender } = render(
      <DateRangePickerCalendar
        locale={locale}
        focus={START_DATE}
        onStartDateChange={handleStartDateChange}
        onEndDateChange={handleEndDateChange}
        onFocusChange={handleFocusChange}
      />
    )

    fireEvent.click(getAllByText('1')[0])

    expect(handleStartDateChange).toHaveBeenCalledTimes(1)
    expect(handleEndDateChange).toHaveBeenCalledTimes(0)
    expect(handleFocusChange).toHaveBeenCalledWith(END_DATE)

    rerender(
      <DateRangePickerCalendar
        locale={locale}
        focus={END_DATE}
        startDate={startOfMonth(new Date())}
        onStartDateChange={handleStartDateChange}
        onEndDateChange={handleEndDateChange}
        onFocusChange={handleFocusChange}
      />
    )

    fireEvent.click(getAllByText('2')[0])

    expect(handleStartDateChange).toHaveBeenCalledTimes(1)
    expect(handleEndDateChange).toHaveBeenCalledTimes(1)
    expect(handleFocusChange).toHaveBeenCalledWith(null)
  })

  it('should display selected date range', () => {
    const startDate = startOfMonth(new Date())
    const endDate = addDays(startDate, 2)

    const { container, getAllByText, rerender } = render(
      <DateRangePickerCalendar locale={locale} startDate={startDate} />
    )

    expect(getAllByText('1')[0].parentElement).toHaveClass('-selected')
    expect(container.querySelectorAll('.-selected').length).toBe(1)

    rerender(<DateRangePickerCalendar locale={locale} startDate={startDate} endDate={endDate} />)

    expect(getAllByText('1')[0].parentElement).toHaveClass('-selected -selected-start')
    expect(getAllByText('2')[0].parentElement).toHaveClass('-selected -selected-middle')
    expect(getAllByText('3')[0].parentElement).toHaveClass('-selected -selected-end')
    expect(container.querySelectorAll('.-selected').length).toBe(3)
  })

  it('should display pre-selected start date’s month on initial render', () => {
    const today = new Date()
    const pastDate = subMonths(today, 1)
    const monthName = format(pastDate, 'LLLL', { locale })

    const { getByText } = render(<DateRangePickerCalendar locale={locale} startDate={pastDate} endDate={today} />)

    expect(getByText(monthName, { exact: false })).toBeInTheDocument()
  })

  it('should display pre-selected end date’s month on initial render', () => {
    const pastDate = subMonths(new Date(), 1)
    const monthName = format(pastDate, 'LLLL', { locale })

    const { getByText } = render(<DateRangePickerCalendar locale={locale} endDate={pastDate} />)

    expect(getByText(monthName, { exact: false })).toBeInTheDocument()
  })

  it('should maintain the selected start date’s time when selecting a new date', () => {
    const handleStartDateChange = jest.fn()

    const { getByText } = render(
      <DateRangePickerCalendar
        locale={locale}
        focus={START_DATE}
        startDate={new Date(2020, 1, 24, 18, 30)}
        onStartDateChange={handleStartDateChange}
      />
    )

    fireEvent.click(getByText('25'))

    expect(handleStartDateChange).toHaveBeenCalledWith(new Date(2020, 1, 25, 18, 30))
  })

  it('should maintain the selected end date’s time when selecting a new date', () => {
    const handleEndDateChange = jest.fn()

    const { getByText } = render(
      <DateRangePickerCalendar
        locale={locale}
        focus={END_DATE}
        endDate={new Date(2020, 1, 24, 18, 30)}
        onEndDateChange={handleEndDateChange}
      />
    )

    fireEvent.click(getByText('25'))

    expect(handleEndDateChange).toHaveBeenCalledWith(new Date(2020, 1, 25, 18, 30))
  })

  it('should allow same day selection by default (when minimumLength is 0)', () => {
    const startDate = startOfDay(set(new Date(), { date: 13 }))

    const { getByText } = render(<DateRangePickerCalendar locale={locale} focus={END_DATE} startDate={startDate} />)

    expect(getByText('13').parentElement).not.toHaveClass('-disabled')
  })

  it('should disable dates before the start date when selecting an end date with no existing end date selected', () => {
    const startDate = startOfDay(set(new Date(), { date: 18 }))

    const { getByText } = render(<DateRangePickerCalendar locale={locale} focus={END_DATE} startDate={startDate} />)

    expect(getByText('16').parentElement).toHaveClass('-disabled')
    expect(getByText('17').parentElement).toHaveClass('-disabled')
    expect(getByText('18').parentElement).not.toHaveClass('-disabled')
  })

  it('should disable dates after the end date when selecting a start date with no existing start date selected', () => {
    const endDate = startOfDay(set(new Date(), { date: 13 }))

    const { getByText } = render(<DateRangePickerCalendar locale={locale} focus={START_DATE} endDate={endDate} />)

    expect(getByText('13').parentElement).not.toHaveClass('-disabled')
    expect(getByText('14').parentElement).toHaveClass('-disabled')
    expect(getByText('15').parentElement).toHaveClass('-disabled')
  })

  it('should disable in-between dates when minimumLength is set', () => {
    const startDate = startOfDay(set(new Date(), { date: 18 }))

    const { getByText } = render(
      <DateRangePickerCalendar locale={locale} focus={END_DATE} startDate={startDate} minimumLength={3} />
    )

    expect(getByText('18').parentElement).toHaveClass('-disabled')
    expect(getByText('19').parentElement).toHaveClass('-disabled')
    expect(getByText('20').parentElement).toHaveClass('-disabled')
    expect(getByText('21').parentElement).not.toHaveClass('-disabled')
  })

  it('should disable in-between dates when selecting start date and minimumLength is set', () => {
    const endDate = startOfDay(set(new Date(), { date: 18 }))

    const { getByText } = render(
      <DateRangePickerCalendar locale={locale} focus={START_DATE} endDate={endDate} minimumLength={3} />
    )

    expect(getByText('18').parentElement).toHaveClass('-disabled')
    expect(getByText('17').parentElement).toHaveClass('-disabled')
    expect(getByText('16').parentElement).toHaveClass('-disabled')
    expect(getByText('15').parentElement).not.toHaveClass('-disabled')
  })

  it('should disable later dates when maximumLength is set', () => {
    const startDate = startOfDay(set(new Date(), { date: 13 }))

    const { getByText } = render(
      <DateRangePickerCalendar locale={locale} focus={END_DATE} startDate={startDate} maximumLength={3} />
    )

    expect(getByText('13').parentElement).not.toHaveClass('-disabled')
    expect(getByText('14').parentElement).not.toHaveClass('-disabled')
    expect(getByText('15').parentElement).not.toHaveClass('-disabled')
    expect(getByText('16').parentElement).not.toHaveClass('-disabled')
    expect(getByText('17').parentElement).toHaveClass('-disabled')
  })

  it('should disable earlier dates when selecting start date and maximumLength is set', () => {
    const endDate = startOfDay(set(new Date(), { date: 18 }))

    const { getByText } = render(
      <DateRangePickerCalendar locale={locale} focus={START_DATE} endDate={endDate} maximumLength={3} />
    )

    expect(getByText('18').parentElement).not.toHaveClass('-disabled')
    expect(getByText('17').parentElement).not.toHaveClass('-disabled')
    expect(getByText('16').parentElement).not.toHaveClass('-disabled')
    expect(getByText('15').parentElement).not.toHaveClass('-disabled')
    expect(getByText('14').parentElement).toHaveClass('-disabled')
  })
})