I'm working on DayPicker
to get all the range dates, but I couldn't have any good idea of knowing the dates between the start date and end date.
import { DateRange, DayPicker } from 'react-day-picker'
const [range, setRange] = useState<DateRange | undefined>()
useEffect(() => {
if(range && range.from && range.to) {
console.log('range.from', range.from)
console.log('range.to', range.to)
// range.from Mon Aug 01 2022 00:00:00 GMT-0700 (Pacific Daylight Time)
// range.to Sat Aug 06 2022 00:00:00 GMT-0700 (Pacific Daylight Time)
// I want get 8/1, 8/2, 8/3, 8/4, 8/5 as string data
}
}, [range])
return (
<DayPicker
mode="range"
defaultMonth={new Date()}
selected={range}
onSelect={setRange}
/>
)
Use date-fns and create a function.
const getDatesInRange = (startDate: Date, numberOfDays: number) => {
const dates: Date[] = [];
[...Array(numberOfDays + 1)].forEach((_, i) => {
dates.push(addDays(startDate, i));
});
console.log(dates); // For debugging purposes
return dates;
};
Add an array state const [dateRangeArray, setDateRangeArray] = useState<Date[]>();
and and we update the useEffect.
Here is the full code:
import { addDays, differenceInDays } from 'date-fns';
// inside the component
const [range, setRange] = useState<DateRange | undefined>();
const [dateRangeArray, setDateRangeArray] = useState<Date[]>();
const getDatesInRange = (startDate: Date, numberOfDays: number) => {
const dates: Date[] = [];
[...Array(numberOfDays + 1)].forEach((_, i) => {
dates.push(addDays(startDate, i));
});
console.log(dates); // For debugging purposes
return dates;
};
useEffect(() => {
if (range && range.to && range.from && dateRangeArray === undefined) {
let daysDiff = differenceInDays(range.to, range?.from);
setDateRangeArray(getDatesInRange(range.from, daysDiff));
}
if (range && range.from && range.to) {
console.log('range.from', range.from);
console.log('range.to', range.to);
// range.from Mon Aug 01 2022 00:00:00 GMT-0700 (Pacific Daylight Time)
// range.to Sat Aug 06 2022 00:00:00 GMT-0700 (Pacific Daylight Time)
// I want get 8/1, 8/2, 8/3, 8/4, 8/5 as string data
}
}, [range]);
return (
<div>
<DayPicker mode='range' defaultMonth={new Date()} selected={range} onSelect={setRange} />
</div>
);