date-fns#addMonths JavaScript Examples
The following examples show how to use
date-fns#addMonths.
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: CalendarNavigation.js From react-nice-dates with MIT License | 6 votes |
export default function CalendarNavigation({ locale, month, minimumDate, maximumDate, onMonthChange }) {
const handlePrevious = event => {
onMonthChange(startOfMonth(subMonths(month, 1)))
event.preventDefault()
}
const handleNext = event => {
onMonthChange(startOfMonth(addMonths(month, 1)))
event.preventDefault()
}
return (
<div className='nice-dates-navigation'>
<a
className={classNames('nice-dates-navigation_previous', {
'-disabled': isSameMonth(month, minimumDate)
})}
onClick={handlePrevious}
onTouchEnd={handlePrevious}
/>
<span className='nice-dates-navigation_current'>
{format(month, getYear(month) === getYear(new Date()) ? 'LLLL' : 'LLLL yyyy', { locale })}
</span>
<a
className={classNames('nice-dates-navigation_next', {
'-disabled': isSameMonth(month, maximumDate)
})}
onClick={handleNext}
onTouchEnd={handleNext}
/>
</div>
)
}
Example #2
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 #3
Source File: MonthView.js From react-horizontal-datepicker with MIT License | 5 votes |
MonthView = ({startDate, lastDate, selectDate, getSelectedDay, primaryColor, labelFormat}) => {
const [selectedDate, setSelectedDate] = useState(null);
const rgb = primaryColor.replace(/[^\d,]/g, '').split(',');
const brightness = Math.round(((parseInt(rgb[0]) * 299) +
(parseInt(rgb[1]) * 587) +
(parseInt(rgb[2]) * 114)) / 1000);
const textColour = (brightness > 125) ? 'black' : 'white';
const selectedStyle = {borderRadius:"0.7rem",background:`${primaryColor}`, color: textColour};
const getStyles = (day) => {
return isSameDay(day, selectedDate)?selectedStyle:null;
};
const getId = (day) => {
return isSameDay(day, selectedDate)?'selected':"";
};
const renderDays = () => {
const months = [];
for (let i = 0; i <= differenceInMonths(lastDate, startDate); i++) {
const month = startOfMonth(addMonths(startDate, i));
months.push(
<div id={`${getId(month)}`}
className={styles.monthContainer}
key={month}
style={getStyles(month)}
onClick={() => onDateClick(month)}
>
<span className={styles.monthYearLabel}>
{format(month, labelFormat || "MMMM yyyy")}
</span>
</div>
);
}
return <div id={"container"} className={styles.dateListScrollable}>{months}</div>;
}
const onDateClick = day => {
setSelectedDate(day);
if (getSelectedDay) {
getSelectedDay(day);
}
};
useEffect(() => {
if (getSelectedDay) {
if (selectDate) {
getSelectedDay(selectDate);
} else {
getSelectedDay(startDate);
}
}
}, []);
useEffect(() => {
if (selectDate) {
if (!isSameDay(selectedDate, selectDate)) {
setSelectedDate(selectDate);
setTimeout(() => {
let view = document.getElementById('selected');
if (view) {
view.scrollIntoView({behavior: "smooth", inline: "center", block: "nearest"});
}
}, 20);
}
}
}, [selectDate]);
return <React.Fragment>{renderDays()}</React.Fragment>
}
Example #4
Source File: date.js From umami with MIT License | 5 votes |
dateFuncs = { minute: [differenceInMinutes, addMinutes, startOfMinute], hour: [differenceInHours, addHours, startOfHour], day: [differenceInCalendarDays, addDays, startOfDay], month: [differenceInCalendarMonths, addMonths, startOfMonth], year: [differenceInCalendarYears, addYears, startOfYear], }
Example #5
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 #6
Source File: DateView.js From react-horizontal-datepicker with MIT License | 4 votes |
DateView = ({
startDate,
lastDate,
selectDate,
getSelectedDay,
primaryColor,
labelFormat
}) => {
const [selectedDate, setSelectedDate] = useState(null);
const firstSection = {
marginLeft: '40px'
};
const selectedStyle = {
fontWeight: "bold",
width: "45px",
height: "45px",
borderRadius: "50%",
border: `2px solid ${primaryColor}`,
color: primaryColor
};
const labelColor = {
color: primaryColor
};
const getStyles = day => {
return isSameDay(day, selectedDate) ? selectedStyle : null;
};
const getId = day => {
return isSameDay(day, selectedDate) ? 'selected' : "";
};
const renderDays = () => {
const dayFormat = "E";
const dateFormat = "d";
const months = [];
let days = [];
for (let i = 0; i <= differenceInMonths(lastDate, startDate); i++) {
let start, end;
const month = startOfMonth(addMonths(startDate, i));
start = i === 0 ? Number(format(startDate, dateFormat)) - 1 : 0;
end = i === differenceInMonths(lastDate, startDate) ? Number(format(lastDate, "d")) : Number(format(lastDayOfMonth(month), "d"));
for (let j = start; j < end; j++) {
let currentDay = addDays(month, j);
days.push( /*#__PURE__*/React.createElement("div", {
id: `${getId(currentDay)}`,
className: styles.dateDayItem,
style: getStyles(currentDay),
key: currentDay,
onClick: () => onDateClick(currentDay)
}, /*#__PURE__*/React.createElement("div", {
className: styles.dayLabel
}, format(currentDay, dayFormat)), /*#__PURE__*/React.createElement("div", {
className: styles.dateLabel
}, format(currentDay, dateFormat))));
}
months.push( /*#__PURE__*/React.createElement("div", {
className: styles.monthContainer,
key: month
}, /*#__PURE__*/React.createElement("span", {
className: styles.monthYearLabel,
style: labelColor
}, format(month, labelFormat || "MMMM yyyy")), /*#__PURE__*/React.createElement("div", {
className: styles.daysContainer,
style: i === 0 ? firstSection : null
}, days)));
days = [];
}
return /*#__PURE__*/React.createElement("div", {
id: "container",
className: styles.dateListScrollable
}, months);
};
const onDateClick = day => {
setSelectedDate(day);
if (getSelectedDay) {
getSelectedDay(day);
}
};
useEffect(() => {
if (getSelectedDay) {
if (selectDate) {
getSelectedDay(selectDate);
} else {
getSelectedDay(startDate);
}
}
}, []);
useEffect(() => {
if (selectDate) {
if (!isSameDay(selectedDate, selectDate)) {
setSelectedDate(selectDate);
setTimeout(() => {
let view = document.getElementById('selected');
if (view) {
view.scrollIntoView({
behavior: "smooth",
inline: "center",
block: "nearest"
});
}
}, 20);
}
}
}, [selectDate]);
return /*#__PURE__*/React.createElement(React.Fragment, null, renderDays());
}
Example #7
Source File: MonthView.js From react-horizontal-datepicker with MIT License | 4 votes |
MonthView = ({
startDate,
lastDate,
selectDate,
getSelectedDay,
primaryColor,
labelFormat
}) => {
const [selectedDate, setSelectedDate] = useState(null);
const rgb = primaryColor.replace(/[^\d,]/g, '').split(',');
const brightness = Math.round((parseInt(rgb[0]) * 299 + parseInt(rgb[1]) * 587 + parseInt(rgb[2]) * 114) / 1000);
const textColour = brightness > 125 ? 'black' : 'white';
const selectedStyle = {
borderRadius: "0.7rem",
background: `${primaryColor}`,
color: textColour
};
const getStyles = day => {
return isSameDay(day, selectedDate) ? selectedStyle : null;
};
const getId = day => {
return isSameDay(day, selectedDate) ? 'selected' : "";
};
const renderDays = () => {
const months = [];
for (let i = 0; i <= differenceInMonths(lastDate, startDate); i++) {
const month = startOfMonth(addMonths(startDate, i));
months.push( /*#__PURE__*/React.createElement("div", {
id: `${getId(month)}`,
className: styles.monthContainer,
key: month,
style: getStyles(month),
onClick: () => onDateClick(month)
}, /*#__PURE__*/React.createElement("span", {
className: styles.monthYearLabel
}, format(month, labelFormat || "MMMM yyyy"))));
}
return /*#__PURE__*/React.createElement("div", {
id: "container",
className: styles.dateListScrollable
}, months);
};
const onDateClick = day => {
setSelectedDate(day);
if (getSelectedDay) {
getSelectedDay(day);
}
};
useEffect(() => {
if (getSelectedDay) {
if (selectDate) {
getSelectedDay(selectDate);
} else {
getSelectedDay(startDate);
}
}
}, []);
useEffect(() => {
if (selectDate) {
if (!isSameDay(selectedDate, selectDate)) {
setSelectedDate(selectDate);
setTimeout(() => {
let view = document.getElementById('selected');
if (view) {
view.scrollIntoView({
behavior: "smooth",
inline: "center",
block: "nearest"
});
}
}, 20);
}
}
}, [selectDate]);
return /*#__PURE__*/React.createElement(React.Fragment, null, renderDays());
}
Example #8
Source File: DateView.js From react-horizontal-datepicker with MIT License | 4 votes |
DateView = ({startDate, lastDate, selectDate, getSelectedDay, primaryColor, labelFormat, marked}) => {
const [selectedDate, setSelectedDate] = useState(null);
const firstSection = {marginLeft: '40px'};
const selectedStyle = {fontWeight:"bold",width:"45px",height:"45px",borderRadius:"50%",border:`2px solid ${primaryColor}`,color:primaryColor};
const labelColor = {color: primaryColor};
const markedStyle = {color: "#8c3737", padding: "2px", fontSize: 12};
const getStyles = (day) => {
return isSameDay(day, selectedDate)?selectedStyle:null;
};
const getId = (day) => {
return isSameDay(day, selectedDate)?'selected':"";
};
const getMarked = (day) => {
let markedRes = marked.find(i => isSameDay(i.date, day));
if (markedRes) {
if (!markedRes?.marked) {
return;
}
return <div style={{ ...markedRes?.style ?? markedStyle }} className={styles.markedLabel}>
{markedRes.text}
</div>;
}
return "";
};
const renderDays = () => {
const dayFormat = "E";
const dateFormat = "d";
const months = [];
let days = [];
// const styleItemMarked = marked ? styles.dateDayItemMarked : styles.dateDayItem;
for (let i = 0; i <= differenceInMonths(lastDate, startDate); i++) {
let start, end;
const month = startOfMonth(addMonths(startDate, i));
start = i === 0 ? Number(format(startDate, dateFormat)) - 1 : 0;
end = i === differenceInMonths(lastDate, startDate) ? Number(format(lastDate, "d")) : Number(format(lastDayOfMonth(month), "d"));
for (let j = start; j < end; j++) {
let currentDay = addDays(month, j);
days.push(
<div id={`${getId(currentDay)}`}
className={marked ? styles.dateDayItemMarked : styles.dateDayItem}
style={getStyles(currentDay)}
key={currentDay}
onClick={() => onDateClick(currentDay)}
>
<div className={styles.dayLabel}>{format(currentDay, dayFormat)}</div>
<div className={styles.dateLabel}>{format(currentDay, dateFormat)}</div>
{getMarked(currentDay)}
</div>
);
}
months.push(
<div className={styles.monthContainer}
key={month}
>
<span className={styles.monthYearLabel} style={labelColor}>
{format(month, labelFormat || "MMMM yyyy")}
</span>
<div className={styles.daysContainer} style={i===0?firstSection:null}>
{days}
</div>
</div>
);
days = [];
}
return <div id={"container"} className={styles.dateListScrollable}>{months}</div>;
}
const onDateClick = day => {
setSelectedDate(day);
if (getSelectedDay) {
getSelectedDay(day);
}
};
useEffect(() => {
if (getSelectedDay) {
if (selectDate) {
getSelectedDay(selectDate);
} else {
getSelectedDay(startDate);
}
}
}, []);
useEffect(() => {
if (selectDate) {
if (!isSameDay(selectedDate, selectDate)) {
setSelectedDate(selectDate);
setTimeout(() => {
let view = document.getElementById('selected');
if (view) {
view.scrollIntoView({behavior: "smooth", inline: "center", block: "nearest"});
}
}, 20);
}
}
}, [selectDate]);
return <React.Fragment>{renderDays()}</React.Fragment>
}
Example #9
Source File: dateFns.js From the-eye-knows-the-garbage with MIT License | 4 votes |
generateConfig = {
// get
getNow: function getNow() {
return new Date();
},
getWeekDay: function getWeekDay(date) {
return getDay(date);
},
getYear: function getYear(date) {
return _getYear(date);
},
getMonth: function getMonth(date) {
return _getMonth(date);
},
getDate: function getDate(date) {
return _getDate(date);
},
getHour: function getHour(date) {
return getHours(date);
},
getMinute: function getMinute(date) {
return getMinutes(date);
},
getSecond: function getSecond(date) {
return getSeconds(date);
},
// set
addYear: function addYear(date, diff) {
return addYears(date, diff);
},
addMonth: function addMonth(date, diff) {
return addMonths(date, diff);
},
addDate: function addDate(date, diff) {
return addDays(date, diff);
},
setYear: function setYear(date, year) {
return _setYear(date, year);
},
setMonth: function setMonth(date, month) {
return _setMonth(date, month);
},
setDate: function setDate(date, num) {
return _setDate(date, num);
},
setHour: function setHour(date, hour) {
return setHours(date, hour);
},
setMinute: function setMinute(date, minute) {
return setMinutes(date, minute);
},
setSecond: function setSecond(date, second) {
return setSeconds(date, second);
},
// Compare
isAfter: function isAfter(date1, date2) {
return _isAfter(date1, date2);
},
isValidate: function isValidate(date) {
return isValid(date);
},
locale: {
getWeekFirstDay: function getWeekFirstDay(locale) {
var clone = Locale[dealLocal(locale)];
return clone.options.weekStartsOn;
},
getWeek: function getWeek(locale, date) {
return _getWeek(date, {
locale: Locale[dealLocal(locale)]
});
},
format: function format(locale, date, _format) {
if (!isValid(date)) {
return null;
}
return formatDate(date, _format, {
locale: Locale[dealLocal(locale)]
});
},
parse: function parse(locale, text, formats) {
for (var i = 0; i < formats.length; i += 1) {
var format = formats[i];
var formatText = text;
var date = parseDate(formatText, format, new Date(), {
locale: Locale[dealLocal(locale)]
});
if (isValid(date)) {
return date;
}
}
return null;
}
}
}