I am using the following in a ReactJS app:
var getDaysArray = function(s, e) {
for (var a = [], d = new Date(s); d <= e; d.setDate(d.getDate() + 1)) {
a.push(new Date(d));
}
return a;
};
const abc = new Date(item.DateTo.toDate()).toISOString().substring(0, 10);
const def = new Date(item.DateFrom.toDate()).toISOString().substring(0, 10);
var daylist = getDaysArray(def, abc);
The DateTo and DateFrom are stored as a firebase timestamp – so am converting this and both abc and def return correct (in console.log) = 2022-05-25 and 2022-05-31 so wondering why this is not working?
daylist always returns an empty array []
>Solution :
The problem here came from the fact you were transforming your dates into
String using the following command : new Date(item.DateTo.toDate()).toISOString().substring(0, 10);
Then you were comparing a string and a date object in your for loop with d <= e
To work with date in JS, you should let them as date as much as possible
const item = {
DateTo: 1653462937961,
DateFrom: 1652997600000,
}
const getDaysArray = function(s, e) {
const a = []
for (let d = new Date(s); d <= e; d.setDate(d.getDate() + 1)) {
a.push(new Date(d));
}
return a;
};
const abc = new Date(item.DateTo)
const def = new Date(item.DateFrom)
var daylist = getDaysArray(def, abc);
console.log(daylist)
Note : Try to avoid use var and rather use const
and as @Louys Patrice Bessette mentioned, you should use meaningful variable names.
For example use startDate instead of s or even dates instead of a