I am developing a student enrollment system where I need to get the months passed since enrollment date and I need to get the start and end dates of the all months passed to date.
let start_date = new Date('2022-01-24 15:00:00');
let months;
months = (current_date.getFullYear() - start_date.getFullYear()) * 12;
months -= start_date.getMonth();
months += current_date.getMonth();
let months_arr = [];
for(let i = 0; i < months; i++){
let start = new Date(start_date.setDate(start_date.getMonth() + i));
let end = new Date(start.setDate(start.getMonth()+1));
months_arr.push({'start': start, 'end': end});
}
return months_arr;
This returns a completely unexpected result:
[
{
"start": "2021-12-12T20:00:00.000Z",
"end": "2021-12-12T20:00:00.000Z"
},
{
"start": "2021-12-12T20:00:00.000Z",
"end": "2021-12-12T20:00:00.000Z"
},
{
"start": "2021-12-12T20:00:00.000Z",
"end": "2021-12-12T20:00:00.000Z"
}
]
How can I do this?
you need to update .setDate to .setMonth
let months_arr = [];
for(let i = 0; i < months; i++){
let start = new Date(start_date.setMonth(start_date.getMonth() + i));
let end = new Date(start.setMonth(start.getMonth()+1));
months_arr.push({'start': start.toISOString(), 'end': end.toISOString()});
}
to add months instead of days,
also i added .toISOString() to format start and end in (ISO 8601)