I would like to make a monthly schedule and have dates dynamically when I change the me and the year and here, to have the dates of the current me I did this function and I don’t understand why it returns me Array(0)
const [moisActuel, setMoisActuel] = useState(new Date())
const genererJoursDuMois = () => {
const jours = []
const debutDuMois = new Date(
moisActuel.getFullYear(),
moisActuel.getMonth(),
1
)
const dernierJourDuMois = new Date(
moisActuel.getFullYear(),
moisActuel.getMonth() + 1,
0
).getDate()
for (
let jour = new Date(debutDuMois);
jour <= dernierJourDuMois;
jour.setDate(jour.getDate() + 1)
) {
jours.push(new Date(jour))
}
return jours
}
const joursDuMois = genererJoursDuMois()
>Solution :
The issue in your code is the comparison in the for loop’s condition: jour <= dernierJourDuMois. Here jour is a Date object and dernierJourDuMois is an integer representing the last day of the month. You’re comparing two different types, which is why it doesn’t work as expected.
Instead, you should create a Date object representing the last day of the month, and compare jour with this Date object.
You can check out this code, I just changed a few lines:
const genererJoursDuMois = () => {
const jours = []
const debutDuMois = new Date(
moisActuel.getFullYear(),
moisActuel.getMonth(),
1
)
// Changed this line to store the date object of the last day of the month, not just the day
const dernierJourDuMois = new Date(
moisActuel.getFullYear(),
moisActuel.getMonth() + 1,
0
)
for (
let jour = new Date(debutDuMois);
// Updated this line to compare jour (Date object) with dernierJourDuMois (also Date object)
jour <= dernierJourDuMois;
jour.setDate(jour.getDate() + 1)
) {
jours.push(new Date(jour))
}
return jours
}
const joursDuMois = genererJoursDuMois()