I have two arrays.
let dateArray = ['2018-05-04T00:00:00+01:00', '2019-04-20T00:00:00+01:00', '2020-05-29T00:00:00+01:00'];
let rangesArray = [['2021-09-01','2022-09-01'],['2019-09-01','2020-09-01']];
How to check if the dates from dateArray are between the dates in rangesArray.
rangesArray[0] is first range - Im interested in dates between 2021-09-01 and 2022-09-01.
rangesArray[1] is second range - Im interested in dates between 2019-09-01 and 2020-09-01.
use Date.parse() to convert string to date for comparison.
working example:
function dateCheck(from, to, check) {
var fDate, lDate, cDate;
fDate = Date.parse(from);
lDate = Date.parse(to);
cDate = Date.parse(check);
if (cDate <= lDate && cDate >= fDate) {
return true;
}
return false;
}
let dateArray = [
"2018-05-04T00:00:00+01:00",
"2019-04-20T00:00:00+01:00",
"2020-05-29T00:00:00+01:00",
];
let rangesArray = [
["2021-09-01", "2022-09-01"],
["2019-09-01", "2020-09-01"],
];
for (let i = 0; i < dateArray.length; i++) {
for (let j = 0; j < rangesArray.length; j++) {
console.log(dateCheck(rangesArray[j][0], rangesArray[j][1], dateArray[i]));
}
}
explanation:
dateCheck function checks if the date is between from date and to date. with two loops you can get the result that you want.
One way :
let dateArray = ['2018-05-04T00:00:00+01:00', '2019-04-20T00:00:00+01:00', '2020-05-29T00:00:00+01:00'];
let rangesArray = [['2021-09-01','2022-09-01'],['2019-09-01','2020-09-01']];
const res = []
dateArray.forEach(d => {
rangesArray.forEach(a => {
if ((new Date(d) >= new Date(a[0])) && (new Date(d) <= new Date(a[1]))){
res.push({date: d, range: a[0] + ' ' + a[1]})
}
})
})
console.log(res)