我有如下数组:
data = [
{
"startDate": "2021-08-18T00:00:04.498059"
"endDate": "2021-08-19T00:00:04.4962889"
},
{
"startDate": "2021-08-18T00:00:04.498059"
"endDate": "2021-08-19T00:00:04.4962889"
}
]
newArray = [];
this.data.foreach(element => {
if((element.startDate - element.endDate) > 7) {
this.newArray.push(element);
}
})
我想遍历上面的数组,并检查对于任何元素,startDate和endDate之间的差异是否大于7天,而不是将该元素推送到新的数组中。
由于日期格式,我不知道我的方法是否正确。我怎么才能正确地做这件事?
发布于 2022-02-10 05:05:42
简单的JavaScript逻辑
逻辑为(1000 * 60 * 60 * 24) => 1000 ms =1秒,60秒=1分钟,60分钟=1小时,24小时=1天。
const data = [
{ "startDate": "2021-08-18T00:00:04.498059", "endDate": "2021-08-19T00:00:04.4962889" },
{ "startDate": "2021-08-18T00:00:04.498059", "endDate": "2021-08-26T00:00:04.4962889" },
{ "startDate": "2021-08-18T00:00:04.498059", "endDate": "2021-08-19T00:00:04.4962889" }
];
const newArray = [];
data.forEach(element => {
const diffTime = new Date(element.endDate) - new Date(element.startDate);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays > 7) {
newArray.push(element);
}
});
console.log(newArray);
发布于 2022-02-10 04:34:57
我想这就是你要找的:
let data = [
{
startDate: "2021-08-18T00:00:04.498059",
endDate: "2021-08-19T00:00:04.4962889",
},
{
startDate: "2021-08-11T00:00:04.498059",
endDate: "2021-08-19T00:00:04.4962889",
}
]
let newArray = [];
data.forEach(element => {
let start = new Date(element.startDate)
let end = new Date(element.endDate)
if((end-start)/1000/60/60/24 > 7)
newArray.push(element);
})
console.log(newArray)
发布于 2022-02-10 04:37:29
const data = [
{
"startDate": "2021-08-18T00:00:04.498059",
"endDate": "2021-08-19T00:00:04.4962889"
},
{
"startDate": "2021-08-18T00:00:04.498059",
"endDate": "2021-08-19T00:00:04.4962889"
}
]
const newData = [];
data.forEach(element => {
const startDate = new Date(element.startDate);
const endDate = new Date(element.endDate);
const difference = endDate.getTime() - startDate.getTime();
if (difference > 604800000) {
newData.push(element);
}
}
);
console.log(newData);https://stackoverflow.com/questions/71059794
复制相似问题