Tabaker78 Tabaker78 - 1 month ago 12
Javascript Question

calculate the number of months between two dates, iterate a function on each month

I'm needing to write a function that takes two dates (startDate, endDate) calculates the time between them in months or years (depending on an input). When the number of months or years is found, I need to iterate a loop that runs a very simple ajax call (I'm adding a record to Quickbase) for every month OR year between the start and end dates.

I've taken a couple of hacks at this but I'm running into trouble when I try to calculate months (due to the calendar dates (i.e. feb having 28 days etc)... I've calculated the time between the two dates in days, but I need months or years.

Any help would be appreciated!


just to start try

function Noofmonths(date1, date2) {
    var Nomonths;
    Nomonths= (date2.getFullYear() - date1.getFullYear()) * 12;
    Nomonths-= date1.getMonth() + 1;
    Nomonths+= date2.getMonth() +1; // we should add + 1 to get correct month number
    return Nomonths <= 0 ? 0 : Nomonths;