Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
JS: Get start and end dates months between two dates

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!