通过比较其他两个日期ReactJS/Javascript之间的日期来过滤JSON列表



我使用这个使用状态挂钩来存储具有相同类型和相同变量的多个对象。

const [objects, setObjects] = useState([]);

当控制台记录挂钩时,这是打印的内容:

[
{
"object_id": 1,
"object_name": "FirstExample",
"date_created": "2021-03-24 14:19:05",
},
{
"object_id": 2,
"object_name": "SecondExample",
"date_created": "2021-03-25 14:19:05",
}
]

问题:

我的问题是,如何过滤JSON列表,使其仅包含StartDate和EndDate变量之间存在date_created属性的对象?

我尝试过,但没有成功,JSON列表变空:

const objectsList = await fetch("http://localhost:5000/objects/all")
const objectListJson = await objectsList.json()
let newList = objectListJson.filter(function(){
return (this).data('date_created') < StartDate || (this).data('date_created') > EndDate;
}).hide();
setObjects(newList);

我也尝试过,但列表再次变为空

setObjects(objectListJson.filter(objectListJson => objectListJson.date_created >= StartDate || objectListJson.date_created <= EndDate ))

比较字符串而不是实际日期。您应该将日期字符串转换为数字。Date.parse("2021-03-24 14:19:05")将返回自1970年1月1日00:00:00 UTC 以来的毫秒数

请这样尝试。

let newList = objectListJson.filter(el => el.date_created >= StartDate && el.date_created < EndDate);

如果StartDateEndDate变量是时间戳,请这样尝试。

let newList = objectListJson.filter(el => Date(el.date_created) >= StartDate && Date(el.date_created) < EndDate);

您应该能够通过将这些日期字符串作为date对象实例进行比较来实现这一点。如果这是一个因素,您还需要指定时区。这里有一个例子:

const objectListJson = [
{
"object_id": 1,
"object_name": "FirstExample",
"date_created": "2021-03-24 14:19:05",
},
{
"object_id": 2,
"object_name": "SecondExample",
"date_created": "2021-03-25 14:19:05",
},
{
"object_id": 3,
"object_name": "SecondExample",
"date_created": "2021-04-01 07:19:05",
}
]
const journalStartDate = new Date(2021, 2, 1) // 2021-03-01 00:00:00
const journalEndDate = new Date(2021, 3, 1) // 2021-04-01 00:00:00
const newList = objectListJson.filter(obj => new Date(obj.date_created) >= journalStartDate && new Date(obj.date_created) < journalEndDate);
//setObjects(newList);
//filters out object 3 because it is not between journalStartDate and journalEndDate
console.log(newList);
.as-console-wrapper { display: block !important; top: 0 !important; max-height: 100% !important; } .as-console { height: 100% !important; } .as-console-row-code { vertical-align: top !important; }

最新更新