reactjs - 如何使用 mui datepicker 在 Reactjs 中过滤从和到特定日期的日期
问题描述
我有一个对象数组“mainData”,如下所示:
0: {date: "2020-07-25T16:44:43.000Z"
description: "Qwerty"
id: 89329972},
1: {date: "2020-07-25T16:46:28.000Z"
description: "Place bins please"
id: 65586316},
2: {date: "2020-07-25T16:49:12.000Z"
description: "Solve sewerege problem"
id: 84687816},
3: {date: "2020-07-26T16:34:47.000Z"
description: "Test compl"
id: 56437370},
4: {date: "2020-07-26T16:34:47.000Z"
description: "Test compl"
id: 56437370},
5: {date: "2020-07-26T16:34:47.000Z"
description: "Test compl"
id: 56437370},
6: {date: "2020-07-27T08:40:34.000Z"
description: "Sewerage problem in my area"
id: 92402221},
7: {date: "2020-07-28T11:42:18.000Z"
description: "problem"
id: 25613902},
8: {date: "2020-08-09T11:42:18.000Z"
description: "problem"
id: 25613902},
9: {date: "2020-08-10T11:42:18.000Z"
description: "problem"
id: 25613902},
现在我允许用户使用 mui datepicker 选择日期和日期。这就是我接收值的方式:
db date new : Sat Jul 25 2020 16:44:43
selected fromDate : Sat Jul 25 2020 22:46:00
selected toDate : Mon Aug 10 2020 22:46:15
第一个 db 日期是 25 日,因为 fromdate 也是 25 日,但由于时间/时区的不同,它们的值会有所不同。
这是我用来过滤掉值的方法:
useEffect(() => {
if (fromDate !== null && toDate !== null) {
setReportData(
mainData.filter(
(obj) => {
console.log("db date new :", new Date(obj.date.substring(0, 19)))
console.log("selected fromDate :",fromDate)
console.log("selected toDate :", toDate)
return new Date(obj.date.substring(0, 19)).getTime() >= fromDate.getTime() && new Date(obj.date.substring(0, 19)).getTime() <= toDate.getTime()
}
)
)
}
}, [toDate])
有了这个,我没有得到日期为 25 日的对象,但我得到了与 toDate 匹配的对象以及这两个日期之间的所有对象。
解决方案
由于您只想按日期过滤并忽略时间,您可以执行以下操作:
useEffect(() => {
if (fromDate !== null && toDate !== null) {
setReportData(
mainData.filter(obj => {
return new Date(obj.date.substring(0, 19)).getTime() >= new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate(), 0, 0, 0).getTime()
&& new Date(obj.date.substring(0, 19)).getTime() <= new Date(toDate.getFullYear(), toDate.getMonth(), toDate.getDate(), 23, 59, 0).getTime()
}
)
)
}
}, [toDate])
所以你告诉你的程序是获取fromDate
和toDate
对象并改变它们的时间,以便在一天的开始和结束。如果您将代码更改为此,您的过滤器将起作用。为了忽略时间,我在 MUI DatePicker 中找不到属性。
new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate(), 0, 0, 0)
new Date(toDate.getFullYear(), toDate.getMonth(), toDate.getDate(), 23, 59, 0)
另一种选择是使用包含时间的日期初始化 DatePickers 的值,例如2020-07-25T00:00:01
,然后选择的每个日期都将“携带”这次。