-1

I wanted to display the selected date range chosen from the date picker. such as when the start date is 04/07 and the end is 08/07, it needs to display the date of the range as 04/07 05/07 06/07 07/07 08/07. But I got a result as 05/07 06/07 07/07 08/07, the start date in the display. help me with this issue to display the selected dates.

the code in code sandbox to : https://codesandbox.io/s/romantic-breeze-yi2qfu?file=/src/App.js

Code :

import "./styles.css";
import moment from "moment";
import React from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

export default function App() {
  const [dateRange, setDateRange] = React.useState([null, null]);
  const [startDate, endDate] = dateRange;
  const startD = dateRange[0];
  const endD = dateRange[1];
  const st = startD && startD.getDate();
  const ed = endD && endD.getDate();
  const rangeDates = moment(startD);
  let dates = [];
  const daterray = [];
  for (let i = st; i < ed; i += 1) {
    dates = rangeDates.add(1, "day");
    daterray.push(dates.format("DD/MM"));
  }
  return (
    <div className="App">
      <DatePicker
        selectsRange
        startDate={startDate}
        endDate={endDate}
        onChange={(update) => {
          setDateRange(update);
        }}
        isClearable
      />
      <div>
        <h5>Selected Dates </h5>
        <p>{daterray}</p>
      </div>
    </div>
  );
}
Lucky
  • 187
  • 13
  • In your for loop, you immediately add 1 to the starting date, never giving a the script a chance to display the first date. Push the date into the array before adding 1. – Brendan Bond Aug 05 '22 at 05:02

1 Answers1

2

You never enter the start date into the array, because you increase the date by one day before entering it into the array. So, you have to not do that, when it is the start date. Something like this should work:

for (let i = st; i < ed; i += 1) {
   if (i == st) {
      dates = rangeDates;
   } else {
      dates = rangeDates.add(1, "day");
   }

   daterray.push(dates.format("DD/MM"));
}
Geshode
  • 3,600
  • 6
  • 18
  • 32