这些是我从Mysql数据库中获得的这种格式的日期,我需要在那里动态获取这个数组中适合现在最后24小时窗口的所有字段。问题是js日期的格式不同,所以我很难用一种干净有效的方式来比较它们。
这是日期数组:
let userTransactions = [
{
id: 1,
created_at: "2022-08-18 12:15:12",
updated_at: "2022-08-19 12:15:12",
},
{
id: 2,
created_at: "2022-08-19 10:15:12",
updated_at: "2022-08-19 12:15:12",
},
{
id: 3,
created_at: "2022-08-19 16:15:12",
updated_at: "2022-08-19 12:15:12",
},
{
id: 4,
created_at: "2022-08-19 05:15:12",
updated_at: "2022-08-19 12:15:12",
},
{
id: 5,
created_at: "2022-08-19 11:15:12",
updated_at: "2022-08-19 12:15:12",
},
{
id: 6,
created_at: "2022-08-19 08:15:12",
updated_at: "2022-08-19 12:15:12",
},
];
这就是功能:
const filterTo24Hours = (userTransactions) => {
let dayTransactions = userTransactions.filter((item) => {
let date = new Date();
// this if statement is written to show what i want to have achieved, this is not working
if (date >= item.created_at && date - 1 <= item.created_at) {
//Do something here
console.log(item.created_at);
}
});
return dayTransactions;
}
如果没有像moment.js这样的大量附加库,您可以将日期转换为毫秒来进行比较。我在24小时内用created_at更改了数组的第一项,所以它返回了一些东西。
let userTransactions = [
{
id: 1,
created_at: "2022-08-26 12:15:12",
updated_at: "2022-08-26 12:15:12",
},
{
id: 2,
created_at: "2022-08-19 10:15:12",
updated_at: "2022-08-19 12:15:12",
},
{
id: 3,
created_at: "2022-08-19 16:15:12",
updated_at: "2022-08-19 12:15:12",
},
{
id: 4,
created_at: "2022-08-19 05:15:12",
updated_at: "2022-08-19 12:15:12",
},
{
id: 5,
created_at: "2022-08-19 11:15:12",
updated_at: "2022-08-19 12:15:12",
},
{
id: 6,
created_at: "2022-08-19 08:15:12",
updated_at: "2022-08-19 12:15:12",
},
];
const filterTo24Hours = (userTransactions) => {
let date = (new Date()).getTime() - 24 * 60 * 60 * 1000;
let dayTransactions = userTransactions.filter((item) => (new Date(item.created_at)).getTime() >= date);
return dayTransactions;
}
console.log(filterTo24Hours(userTransactions));
const filterTo24Hours = (userTransactions) => {
let dayTransactions = userTransactions.filter((item) => {
// reduce 1 day from current time
let date = Date.now() - 86400000;
// this if statement is written to show what i want to have achieved, this is not working
// created date converted to UTC time by default
if (date < new Date(item.created_at).getTime()) {
//Do something here
//console.log(item.created_at);
return item
}
});
return dayTransactions;
}