我有一个日期数组,我想对其进行排序并仅获取最近的日期
[
"Mon Jul 16 2018 11:40:28 GMT+0200 (CEST)",
"Fri Jul 13 2018 09:33:46 GMT+0200 (CEST)",
"Fri Jul 13 2018 09:21:36 GMT+0200 (CEST)",
"Fri Jul 13 2018 09:03:42 GMT+0200 (CEST)",
"Fri Jul 13 2018 09:01:05 GMT+0200 (CEST)",
"Fri Jul 13 2018 08:53:23 GMT+0200 (CEST)",
"Fri Jul 13 2018 08:52:33 GMT+0200 (CEST)",
"Thu Jul 12 2018 13:41:59 GMT+0200 (CEST)",
"Thu Jul 12 2018 13:41:49 GMT+0200 (CEST)",
"Thu Jul 12 2018 13:41:42 GMT+0200 (CEST)"
]
shouldDisplayDate(date: Date) {
datesFiltered = [];
const array = this.users.map(a => a.date)
for (const date of array) {
if (!this.datesFiltered.find(d => new Date(d).setHours(0, 0, 0) ===
new Date(dateString).setHours(0, 0, 0))) {
this.datesFiltered.push(new Date(dateString).toString())
}
}
}
结果:
[
Mon Jul 16 2018 15:32:50 GMT+0200 (Central European Summer Time),
Fri Jul 13 2018 09:33:46 GMT+0200 (Central European Summer Time),
Thu Jul 12 2018 13:41:59 GMT+0200 (Central European Summer Time)
]
所以我想检查是否输入Mon Jul 16 2018 11:40:28 GMT+0200 (CEST)
是否在对象数组中?
答案 0 :(得分:0)
要使用===
查看两个日期是否相等,您必须首先在它们上使用.getTime()
(请参见this answer for more info)
下面是进行简单日期排序并查找数组中是否存在日期的示例。
要检查日期是否存在于数组中,我首先将字符串日期(我们正在寻找存在的日期)转换为Date obj。然后,我遍历现有日期数组,一次将其转换一次,然后在每个日期上使用Date.getTime()
以查看它们是否相等,如果相等,则该函数将返回true。
const dates = [
"Thu Jul 12 2018 13:41:42 GMT+0200 (CEST)",
"Fri Jul 13 2018 09:03:42 GMT+0200 (CEST)",
"Thu Jul 12 2018 13:41:59 GMT+0200 (CEST)",
"Fri Jul 13 2018 09:33:46 GMT+0200 (CEST)",
"Mon Jul 16 2018 11:40:28 GMT+0200 (CEST)",
"Fri Jul 13 2018 08:53:23 GMT+0200 (CEST)",
"Fri Jul 13 2018 08:52:33 GMT+0200 (CEST)",
"Thu Jul 12 2018 13:41:49 GMT+0200 (CEST)",
"Fri Jul 13 2018 09:21:36 GMT+0200 (CEST)",
"Fri Jul 13 2018 09:01:05 GMT+0200 (CEST)"
];
// simple date sort
let sortedDates = dates.sort(function(a, b) {
return new Date(b) - new Date(a);
});
console.log(`sorted Dates array is: ${JSON.stringify(sortedDates, null, 2)}`);
console.log(`date exists in array? ${isDateInArray("Mon Jul 16 2018 11:40:28 GMT+0200 (CEST)")}`);
function isDateInArray(dateString) {
let dateExists = false;
let date = new Date(dateString);
dates.forEach(function(arrayDateString) {
let arrayDate = new Date(arrayDateString);
if(date.getTime() === arrayDate.getTime()){
dateExists = true;
}
});
return dateExists;
}