简体   繁体   English

如何在反应js中的日期选择器中显示选定的日期范围

[英]How to display the selected dates range in the datepicker in react js

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.如开始日期为04/07,结束日期为08/07,则需要显示范围的日期为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.但我得到的结果是 05/07 06/07 07/07 08/07,显示中的开始日期。 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代码沙箱中的代码为: 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> ); }

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"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM