Krypton Krypton - 1 year ago 82
jQuery Question

Jquery Countdown how to calculate remaining Months from 0-12?

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),

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download