0

Possible Duplicate:
Difference in Months between two dates in JavaScript

<input type="text" id="month1" value="11"><input type="text" id="year1" value="1988"> <br />
<input type="text" id="month2" value="03"><input type="text" id="year2" value="2010"> <br />

<input type="submit" id="show">

$("#show").click(function(){
  var m1 = $("#month1").val();
  var m2 = $("#month2").val();
  var y1 = $("#year1").val();
  var y2 = $("#year2").val();

  var result = 'result';
})

LIVE: http://jsfiddle.net/4XJUp/

How is the best and simply way for count month between two dates in jQuery in this example?

Community
  • 1
  • 1
Martin Sowning
  • 393
  • 2
  • 5
  • 16
  • Simplest way would probably be to subtract one year from the other and than multiply by 12. – Gregg B Nov 22 '11 at 12:55
  • 2
    How are you validating input? Have you considered a date picker? Is a difference 1 day within the same month considered 1 or 0? Is a difference of 30 days within the same month considered as 2 or 1 or 0 (Since that's more than 4 weeks and the length of the shortest month, except in a leap year). – StuperUser Nov 22 '11 at 12:58
  • @Grillz That assumes valid dates, it doesn't take into account the months, whether the earlier month is in the second box or vice versa. – StuperUser Nov 22 '11 at 12:59

1 Answers1

2

Try:

<form onsubmit="monthDiff(this); return false;">
  <br>month&nbsp;1<input id="m1" value="1">
      year&nbsp;1<input id="y1" value="2010">
  <br>month&nbsp;2<input id="m2" value="3">
      year&nbsp;2<input id="y2" value="2010">
  <br>Difference in months:<input id="diff">
  <br><input type="submit">
</form>

<script>

function monthDiff(f) {

  f.diff.value = f.y2.value * 12 + Number(f.m2.value) -
                 f.y1.value * 12 - f.m1.value;
}

</script>

Of course you should validate the input before using it.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Why answer a question that is clearly an exact dupe? – James Hill Nov 22 '11 at 13:18
  • 1
    Probably because it was quicker to just answer it than look for a duplicate. Anyway, I don't think it's an exact duplicate - one uses Date objets, this uses just date strings. Lastly, my solution is better than any for the "duplicate". :-) – RobG Nov 29 '11 at 12:02
  • Alex K., KooiInc, Šime Vidas, Donal Fellows, and I disagree with you :) – James Hill Nov 29 '11 at 12:45