Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 189
  • Last Modified:

calculate the difference between dates

I need to calculate the difference between dates, as to get the number of months between them.

Please advice.
0
sahnias
Asked:
sahnias
  • 2
  • 2
1 Solution
 
nschaferCommented:
Hi sahnias,
Try the following function

  <script type="text/javascript">
    function daysDiff(x,y) {
      return((x - y)/(1000*60*60*24));
    }
   
   var sDate = new Date('01/01/2005')
   var eDate = new Date('01/01/2006')
   alert(daysDiff(eDate,sDate));
  </script>

Hope this helps,
Neal.
0
 
sahniasAuthor Commented:
this will give me days difference... and i have that code already... however how do i get the months difference.
0
 
nschaferCommented:
sahnias,
Sorry about that.  I guess I need to learn to read better.  

This should work for you.

    function monthsDiff(x,y) {
      var smonth = y.getMonth();
      var emonth = x.getMonth();
      var syear = y.getFullYear();
      var eyear = x.getFullYear();
      var months = (eyear - syear) * 12 + emonth - smonth
      if (y.getDate() > x.getDate()) months -=1;
      return months;
    }
   
   var sDate = new Date('03/15/2005')
   var eDate = new Date('01/01/2006')
   alert(monthsDiff(eDate,sDate));


Neal.
0
 
Pravin AsarCommented:
NO POINTS Please. As I am posting a link to my post.

http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_21566387.html
0
 
Pravin AsarCommented:
<SCRIPT LANGUAGE="JavaScript">
function CalculateDiff(d1, d2) {
var date1 = new Date (d1);
var date2 = new Date (d2);
var diff ;
if (date1 > date2) {
diff = date1 - date2;
}
else {
diff = date2 - date1;
}
diff = new Date (diff);

// Difference in months

alert ('Difference in Months : ' + diff.getMonth()+1);

}
CalculateDiff ('01/05/2006', '07/19/2006');
</script>
0

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now