-3

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!

Tabaker78
  • 49
  • 1
  • 1
  • 9

2 Answers2

5

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;
}
Pankaj Anupam
  • 580
  • 4
  • 13
Sajad Karuthedath
  • 14,987
  • 4
  • 32
  • 49
  • This worked great on getting the months. Another question though. What if the start and end date don't have the same day of the month? I.e. startDate == 10-26-2004 && endDate == 10-16-2006? There is a remainder of days, and I'm lost as to what logic finds this. – Tabaker78 May 04 '14 at 20:07
1

obtain date1 year and date2 year. get the difference and multiply by 12. obtain date1 month and date2 month. get the difference. add the differences together.

SDMulroy
  • 54
  • 6