date-fns#isBefore JavaScript Examples
The following examples show how to use
date-fns#isBefore.
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: RealtimeChart.js From umami with MIT License | 6 votes |
export default function RealtimeChart({ data, unit, ...props }) {
const endDate = startOfMinute(new Date());
const startDate = subMinutes(endDate, REALTIME_RANGE);
const prevEndDate = useRef(endDate);
const chartData = useMemo(() => {
if (data) {
return {
pageviews: getDateArray(mapData(data.pageviews), startDate, endDate, unit),
sessions: getDateArray(mapData(data.sessions), startDate, endDate, unit),
};
}
return { pageviews: [], sessions: [] };
}, [data]);
// Don't animate the bars shifting over because it looks weird
const animationDuration = useMemo(() => {
if (isBefore(prevEndDate.current, endDate)) {
prevEndDate.current = endDate;
return 0;
}
return DEFAULT_ANIMATION_DURATION;
}, [data]);
return (
<PageviewsChart
{...props}
height={200}
unit={unit}
data={chartData}
animationDuration={animationDuration}
/>
);
}
Example #2
Source File: utils.js From nyc-makers-vs-covid with GNU General Public License v3.0 | 6 votes |
export function shouldFormatDateDistance(date) {
let deliveryDate = parse(date, 'MM/dd/yyyy', new Date())
let fourDaysFromDeliveryDate = addDays(deliveryDate, 4)
return isBefore(startOfToday(), fourDaysFromDeliveryDate)
}
Example #3
Source File: common-functions.js From covid19Nepal-react with MIT License | 6 votes |
validateCTS = (data = []) => {
const dataTypes = [
'dailyconfirmed',
'dailydeceased',
'dailyrecovered',
'totalconfirmed',
'totaldeceased',
'totalrecovered',
];
return data
.filter((d) => dataTypes.every((dt) => d[dt]) && d.date)
.filter((d) => dataTypes.every((dt) => Number(d[dt]) >= 0))
.filter((d) => {
// Skip data from the current day
const today = getNepalDay();
const date = parse(d.date, 'dd MMMM', new Date(2020, 0, 1));
return isBefore(date, today);
});
}
Example #4
Source File: common-functions.js From covid19Nepal-react with MIT License | 6 votes |
parseStateTestTimeseries = (data) => {
const stateCodeMap = Object.keys(STATE_CODES).reduce((ret, sc) => {
ret[STATE_CODES[sc]] = sc;
return ret;
}, {});
const testTimseries = Object.keys(STATE_CODES).reduce((ret, sc) => {
ret[sc] = [];
return ret;
}, {});
const today = getNepalDay();
data.forEach((d) => {
const date = parse(d.updatedon, 'dd/MM/yyyy', new Date());
const totaltested = +d.totaltested;
if (isBefore(date, today) && totaltested) {
const stateCode = stateCodeMap[d.state];
testTimseries[stateCode].push({
date: date,
totaltested: totaltested,
});
}
});
return testTimseries;
}
Example #5
Source File: common-functions.js From covid19Nepal-react with MIT License | 6 votes |
parseTotalTestTimeseries = (data) => {
const testTimseries = [];
const today = getNepalDay();
data.forEach((d) => {
const date = parse(
d.updatetimestamp.split(' ')[0],
'dd/MM/yyyy',
new Date()
);
const totaltested = +d.totalsamplestested;
if (isBefore(date, today) && totaltested) {
let dailytested;
if (testTimseries.length) {
const prev = testTimseries[testTimseries.length - 1];
if (isSameDay(date, prev.date)) {
prev.dailytested += totaltested - prev.totaltested;
prev.totaltested = totaltested;
} else {
if (differenceInDays(date, prev.date) === 1)
dailytested = totaltested - prev.totaltested;
else dailytested = NaN;
}
} else dailytested = NaN;
testTimseries.push({
date: date,
totaltested: totaltested,
dailytested: dailytested,
});
}
});
return testTimseries;
}
Example #6
Source File: index.js From ftx-cli with MIT License | 6 votes |
function calculateMillisecondsUntilDate(date) {
const currentDate = new Date();
const scheduleDate = parseISO(date);
if (!isValid(scheduleDate)) {
return null;
}
if (isBefore(scheduleDate, currentDate)) {
return null;
}
return differenceInMilliseconds(scheduleDate, currentDate);
}
Example #7
Source File: Calendar.js From umami with MIT License | 6 votes |
MonthSelector = ({ date, minDate, maxDate, locale, onSelect }) => {
const start = startOfYear(date);
const months = [];
for (let i = 0; i < 12; i++) {
months.push(addMonths(start, i));
}
function handleSelect(value) {
onSelect(setMonth(date, value));
}
return (
<table>
<tbody>
{chunk(months, 3).map((row, i) => (
<tr key={i}>
{row.map((month, j) => {
const disabled =
isBefore(endOfMonth(month), minDate) || isAfter(startOfMonth(month), maxDate);
return (
<td
key={j}
className={classNames(locale, {
[styles.selected]: month.getMonth() === date.getMonth(),
[styles.disabled]: disabled,
})}
onClick={!disabled ? () => handleSelect(month.getMonth()) : null}
>
{dateFormat(month, 'MMMM', locale)}
</td>
);
})}
</tr>
))}
</tbody>
</table>
);
}
Example #8
Source File: index.js From react-timeline-range-slider with MIT License | 6 votes |
getFormattedBlockedIntervals = (blockedDates = [], [startTime, endTime]) => {
if (!blockedDates.length) return null
const timelineLength = differenceInMilliseconds(endTime, startTime)
const getConfig = getTimelineConfig(startTime, timelineLength)
const formattedBlockedDates = blockedDates.map((interval, index) => {
let { start, end } = interval
if (isBefore(start, startTime)) start = startTime
if (isAfter(end, endTime)) end = endTime
const source = getConfig(start)
const target = getConfig(end)
return { id: `blocked-track-${index}`, source, target }
})
return formattedBlockedDates
}
Example #9
Source File: utils.js From react-nice-dates with MIT License | 6 votes |
isSelectable = (date, { minimumDate, maximumDate }) =>
!isBefore(date, startOfDay(minimumDate)) && !isAfter(date, maximumDate)
Example #10
Source File: DeliveryFinishController.js From FastFeet with MIT License | 5 votes |
async update(req, res) {
const { id, deliveryId } = req.params;
const { signatureId } = req.body;
if (
!(await Deliveryman.findOne({
where: { id }
}))
)
res.status(400).json({ error: 'Deliveryman does not exists' });
const delivery = await Delivery.findOne({
where: {
id: deliveryId,
start_date: {
[Op.ne]: null
}
}
});
if (!delivery) {
return res.status(400).json({
error: "Delivery doesn't exists or has not yet been withdrawn"
});
}
if (delivery.signature_id) {
return res
.status(400)
.json({ error: 'This order has already been delivered' });
}
if (isBefore(new Date(), delivery.start_date)) {
return res.status(400).json({
error: 'Delivery date must be after the withdrawal date'
});
}
const signature = await File.findByPk(signatureId);
if (!signature) {
return res.status(400).json({
error: 'Signature does not found!'
});
}
await delivery.update({
end_date: new Date(),
signature_id: signatureId
});
return res.json(delivery);
}
Example #11
Source File: DatePickerForm.js From umami with MIT License | 5 votes |
export default function DatePickerForm({
startDate: defaultStartDate,
endDate: defaultEndDate,
minDate,
maxDate,
onChange,
onClose,
}) {
const [selected, setSelected] = useState(
isSameDay(defaultStartDate, defaultEndDate) ? FILTER_DAY : FILTER_RANGE,
);
const [date, setDate] = useState(defaultStartDate);
const [startDate, setStartDate] = useState(defaultStartDate);
const [endDate, setEndDate] = useState(defaultEndDate);
const disabled =
selected === FILTER_DAY
? isAfter(minDate, date) && isBefore(maxDate, date)
: isAfter(startDate, endDate);
const buttons = [
{
label: <FormattedMessage id="label.single-day" defaultMessage="Single day" />,
value: FILTER_DAY,
},
{
label: <FormattedMessage id="label.date-range" defaultMessage="Date range" />,
value: FILTER_RANGE,
},
];
function handleSave() {
if (selected === FILTER_DAY) {
onChange({ ...getDateRangeValues(date, date), value: 'custom' });
} else {
onChange({ ...getDateRangeValues(startDate, endDate), value: 'custom' });
}
}
return (
<div className={styles.container}>
<div className={styles.filter}>
<ButtonGroup size="small" items={buttons} selectedItem={selected} onClick={setSelected} />
</div>
<div className={styles.calendars}>
{selected === FILTER_DAY ? (
<Calendar date={date} minDate={minDate} maxDate={maxDate} onChange={setDate} />
) : (
<>
<Calendar
date={startDate}
minDate={minDate}
maxDate={endDate}
onChange={setStartDate}
/>
<Calendar date={endDate} minDate={startDate} maxDate={maxDate} onChange={setEndDate} />
</>
)}
</div>
<FormButtons>
<Button variant="action" onClick={handleSave} disabled={disabled}>
<FormattedMessage id="label.save" defaultMessage="Save" />
</Button>
<Button onClick={onClose}>
<FormattedMessage id="label.cancel" defaultMessage="Cancel" />
</Button>
</FormButtons>
</div>
);
}
Example #12
Source File: Calendar.js From umami with MIT License | 5 votes |
DaySelector = ({ date, minDate, maxDate, locale, onSelect }) => {
const dateLocale = getDateLocale(locale);
const weekStartsOn = dateLocale?.options?.weekStartsOn || 0;
const startWeek = startOfWeek(date, {
locale: dateLocale,
weekStartsOn,
});
const startMonth = startOfMonth(date);
const startDay = subDays(startMonth, startMonth.getDay() - weekStartsOn);
const month = date.getMonth();
const year = date.getFullYear();
const daysOfWeek = [];
for (let i = 0; i < 7; i++) {
daysOfWeek.push(addDays(startWeek, i));
}
const days = [];
for (let i = 0; i < 35; i++) {
days.push(addDays(startDay, i));
}
return (
<table>
<thead>
<tr>
{daysOfWeek.map((day, i) => (
<th key={i} className={locale}>
{dateFormat(day, 'EEE', locale)}
</th>
))}
</tr>
</thead>
<tbody>
{chunk(days, 7).map((week, i) => (
<tr key={i}>
{week.map((day, j) => {
const disabled = isBefore(day, minDate) || isAfter(day, maxDate);
return (
<td
key={j}
className={classNames({
[styles.selected]: isSameDay(date, day),
[styles.faded]: day.getMonth() !== month || day.getFullYear() !== year,
[styles.disabled]: disabled,
})}
onClick={!disabled ? () => onSelect(day) : null}
>
{day.getDate()}
</td>
);
})}
</tr>
))}
</tbody>
</table>
);
}
Example #13
Source File: useGrid.js From react-nice-dates with MIT License | 5 votes |
reducer = (state, action) => {
switch (action.type) {
case 'setStartDate':
return { ...state, startDate: action.value }
case 'setEndDate':
return { ...state, endDate: action.value }
case 'setRange':
return { ...state, startDate: action.startDate, endDate: action.endDate }
case 'setCellHeight':
return { ...state, cellHeight: action.value }
case 'setIsWide':
return { ...state, isWide: action.value }
case 'reset':
return {
...createInitialState(action.currentMonth, state.locale),
cellHeight: state.cellHeight,
isWide: state.isWide
}
case 'transitionToCurrentMonth': {
const { currentMonth } = action
const { lastCurrentMonth, startDate, endDate, cellHeight } = state
const newState = {
...state,
lastCurrentMonth: currentMonth,
transition: true
}
if (isAfter(currentMonth, lastCurrentMonth)) {
const offset = -(rowsBetweenDates(startDate, currentMonth, state.locale) - 1) * cellHeight
return {
...newState,
endDate: getEndDate(currentMonth, state.locale),
offset,
origin: ORIGIN_TOP
}
} else if (isBefore(currentMonth, lastCurrentMonth)) {
const gridHeight = cellHeight * 6
const offset = rowsBetweenDates(currentMonth, endDate, state.locale) * cellHeight - gridHeight
return {
...newState,
startDate: getStartDate(currentMonth, state.locale),
offset,
origin: ORIGIN_BOTTOM
}
}
return state
}
default:
throw new Error(`Unknown ${action.type} action type`)
}
}
Example #14
Source File: common-functions.js From covid19Nepal-react with MIT License | 5 votes |
parseStateTimeseries = ({states_daily: data}) => {
const statewiseSeries = Object.keys(STATE_CODES).reduce((a, c) => {
a[c] = [];
return a;
}, {});
const today = getNepalDay();
for (let i = 0; i < data.length; i += 3) {
const date = parse(data[i].date, 'dd-MMM-yy', new Date());
// Skip data from the current day
if (isBefore(date, today)) {
Object.entries(statewiseSeries).forEach(([k, v]) => {
const stateCode = k.toLowerCase();
const prev = v[v.length - 1] || {};
// Parser
const dailyconfirmed = +data[i][stateCode] || 0;
const dailyrecovered = +data[i + 1][stateCode] || 0;
const dailydeceased = +data[i + 2][stateCode] || 0;
const totalconfirmed = +data[i][stateCode] + (prev.totalconfirmed || 0);
const totalrecovered =
+data[i + 1][stateCode] + (prev.totalrecovered || 0);
const totaldeceased =
+data[i + 2][stateCode] + (prev.totaldeceased || 0);
// Push
v.push({
date: date,
dailyconfirmed: dailyconfirmed,
dailyrecovered: dailyrecovered,
dailydeceased: dailydeceased,
totalconfirmed: totalconfirmed,
totalrecovered: totalrecovered,
totaldeceased: totaldeceased,
// Active = Confimed - Recovered - Deceased
totalactive: totalconfirmed - totalrecovered - totaldeceased,
dailyactive: dailyconfirmed - dailyrecovered - dailydeceased,
});
});
}
}
return statewiseSeries;
}
Example #15
Source File: DeliveryDashboardController.js From FastFeet with MIT License | 5 votes |
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 #16
Source File: useGrid.js From react-nice-dates with MIT License | 4 votes |
export default function useGrid({ locale, month: currentMonth, onMonthChange, transitionDuration, touchDragEnabled }) {
const timeoutRef = useRef()
const containerElementRef = useRef()
const initialDragPositionRef = useRef(0)
const [state, dispatch] = useReducer(reducer, createInitialState(currentMonth, locale))
const { startDate, endDate, cellHeight, lastCurrentMonth, offset, origin, transition, isWide } = state
useLayoutEffect(() => {
const notDragging = !initialDragPositionRef.current
if (!isSameMonth(lastCurrentMonth, currentMonth) && notDragging) {
const containerElement = containerElementRef.current
containerElement.classList.add('-transition')
clearTimeout(timeoutRef.current)
if (Math.abs(differenceInCalendarMonths(currentMonth, lastCurrentMonth)) <= 3) {
dispatch({ type: 'transitionToCurrentMonth', currentMonth })
timeoutRef.current = setTimeout(() => {
dispatch({ type: 'reset', currentMonth })
}, transitionDuration)
} else {
dispatch({ type: 'reset', currentMonth })
}
}
}, [currentMonth]) // eslint-disable-line react-hooks/exhaustive-deps
useLayoutEffect(() => {
if (!touchDragEnabled) {
return
}
const containerElement = containerElementRef.current
const gridHeight = cellHeight * 6
const halfGridHeight = gridHeight / 2
if (containerElement) {
const handleDragStart = event => {
clearTimeout(timeoutRef.current)
const computedOffset = Number(window.getComputedStyle(containerElement).transform.match(/([-+]?[\d.]+)/g)[5])
let currentMonthPosition = 0
if (!initialDragPositionRef.current) {
const newStartDate = getStartDate(subMonths(currentMonth, 1), locale)
currentMonthPosition = (rowsBetweenDates(newStartDate, currentMonth, locale) - 1) * cellHeight
dispatch({ type: 'setRange', startDate: newStartDate, endDate: getEndDate(addMonths(currentMonth, 1), locale) })
}
containerElement.style.transform = `translate3d(0, ${computedOffset || -currentMonthPosition}px, 0)`
containerElement.classList.remove('-transition')
containerElement.classList.add('-moving')
initialDragPositionRef.current = event.touches[0].clientY + (-computedOffset || currentMonthPosition)
}
const handleDrag = event => {
const initialDragPosition = initialDragPositionRef.current
const dragOffset = event.touches[0].clientY - initialDragPosition
const previousMonth = subMonths(currentMonth, 1)
const previousMonthPosition = (rowsBetweenDates(startDate, previousMonth, locale) - 1) * cellHeight
const currentMonthPosition = (rowsBetweenDates(startDate, currentMonth, locale) - 1) * cellHeight
const nextMonth = addMonths(currentMonth, 1)
const nextMonthPosition = (rowsBetweenDates(startDate, nextMonth, locale) - 1) * cellHeight
if (dragOffset < 0) {
if (Math.abs(dragOffset) > currentMonthPosition && isBefore(endDate, addMonths(currentMonth, 2))) {
dispatch({ type: 'setEndDate', value: getEndDate(nextMonth, locale) })
}
} else if (dragOffset > 0) {
const newStartDate = getStartDate(previousMonth, locale)
const newCurrentMonthPosition = (rowsBetweenDates(newStartDate, currentMonth, locale) - 1) * cellHeight
initialDragPositionRef.current += newCurrentMonthPosition
dispatch({ type: 'setStartDate', value: newStartDate })
}
const shouldChangeToNextMonth = Math.abs(dragOffset) > nextMonthPosition - halfGridHeight
const shouldChangeToPreviousMonth =
Math.abs(dragOffset) > previousMonthPosition - halfGridHeight &&
Math.abs(dragOffset) < currentMonthPosition - halfGridHeight
if (shouldChangeToNextMonth) {
onMonthChange(nextMonth)
} else if (shouldChangeToPreviousMonth) {
onMonthChange(previousMonth)
}
containerElement.style.transform = `translate3d(0, ${dragOffset}px, 0)`
event.preventDefault()
}
const handleDragEnd = event => {
const currentMonthPosition = (rowsBetweenDates(startDate, currentMonth, locale) - 1) * cellHeight
containerElement.style.transform = `translate3d(0, ${-currentMonthPosition}px, 0)`
containerElement.classList.add('-transition')
containerElement.classList.remove('-moving')
timeoutRef.current = setTimeout(() => {
initialDragPositionRef.current = 0
containerElement.style.transform = 'translate3d(0, 0, 0)'
containerElement.classList.remove('-transition')
dispatch({ type: 'reset', currentMonth: currentMonth })
}, transitionDuration)
if (Math.abs(initialDragPositionRef.current - currentMonthPosition - event.changedTouches[0].clientY) > 10) {
event.preventDefault()
event.stopPropagation()
}
}
containerElement.addEventListener('touchstart', handleDragStart)
containerElement.addEventListener('touchmove', handleDrag)
containerElement.addEventListener('touchend', handleDragEnd)
return () => {
containerElement.removeEventListener('touchstart', handleDragStart)
containerElement.removeEventListener('touchmove', handleDrag)
containerElement.removeEventListener('touchend', handleDragEnd)
}
}
})
useEffect(() => {
const handleResize = () => {
const containerElement = containerElementRef.current
const containerWidth = containerElement.offsetWidth
const cellWidth = containerWidth / 7
let newCellHeight = 1
let wide = false
if (cellWidth > 60) {
newCellHeight += Math.round(cellWidth * 0.75)
wide = true
} else {
newCellHeight += Math.round(cellWidth)
}
dispatch({ type: 'setIsWide', value: wide })
dispatch({ type: 'setCellHeight', value: newCellHeight })
}
window.addEventListener('resize', handleResize)
handleResize()
return () => {
window.removeEventListener('resize', handleResize)
}
}, [])
return {
startDate,
endDate,
cellHeight,
containerElementRef,
offset,
origin,
transition,
isWide
}
}
Example #17
Source File: DateRangePickerCalendar.js From react-nice-dates with MIT License | 4 votes |
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}
/>
)
}