0

What's the best way to calculate the remaining months left on a countdown timer?

I'm using jquery to countdown to a date in the future that is over 12 months away, in fact far longer than 10 years away.

How would I show months from 0-12 based on how much time is left? So for example the timer could show x Years and 5 Months remaining resetting to 12 once it hits 0.

I'll be replacing the "weeks" with months, but I'm not sure how to calculate it.

                weeks = Math.floor(left/60/60/24/7),
Krypton
  • 118
  • 12

1 Answers1

2

I think this may be what you're looking for:

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
}

Source: Difference in Months between two dates in JavaScript

That will give you the total number of months between the two dates, after which you can use the modulus operator to get the number you need: monthDiff(yourDate1, yourDate2) % 12

Community
  • 1
  • 1
MJH
  • 2,301
  • 7
  • 18
  • 20
  • He He! Why thank you sir, worked like a charm :) As soon as I find the link to mark this as the answer you got it! For anyone else wondering, I had a little trouble calling the function using the current date as one of the variables (who knows why I think I had an extra set of brackets) but this works - `monthDiff(new Date(), yourDate2 ) % 12,` – Krypton Aug 29 '16 at 04:11