如何使用 mui datepicker 在 Reactjs 中过滤特定日期的日期

How to filter dates from and to a particular date in Reactjs using mui datepicker

我有一个对象数组“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 日期选择器 select 从和到日期。这就是我接收值的方式:

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

第一个数据库日期是 25 日,因为开始日期也是 25 日,但由于 time/timezone 的差异,它们的值会有所不同。

这是我用来过滤值的:


 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])

所以你告诉你的程序是获取 fromDatetoDate 对象并更改它们的时间,以便在一天的开始和结束。 如果您将代码更改为此,您的过滤器将起作用。为了忽略时间,我在 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 然后每个选择的日期都将“携带”这次。