0

I'm trying to calculate the distance between two dates using Javascript. Right now I've found some great code that works really well, but it has one problem. Whenever I try to calculate dates across months that have 30 days instead of 31, it calculates an extra day (I guess because it assumes every month has 31 days). I'm wondering if there's any way to fix this?

    var from = document.getElementById("from").value;
    var fromdate = from.slice(3, 5);
    fromdate = parseInt(fromdate);
    var frommonth = from.slice(0, 2); 
    frommonth = parseInt(frommonth);
    var fromyear = from.slice(6, 10); 
    fromyear = parseInt(fromyear);
    var to = document.getElementById("to").value;
    var todate = to.slice(3, 5); 
    todate = parseInt(todate);
    var tomonth = to.slice(0, 2); 
    tomonth = parseInt(tomonth);
    var toyear = to.slice(6, 10); 
    toyear = parseInt(toyear);
    var oneDay = 24*60*60*1000;
    var firstDate = new Date(fromyear,frommonth,fromdate);
    var secondDate = new Date(toyear,tomonth,todate);

    var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
    alert(diffDays);
user3688016
  • 23
  • 1
  • 5
  • 1
    This has been answered here: http://stackoverflow.com/questions/4944750/how-to-subtract-date-time-in-javascript – SDM Jun 27 '14 at 14:37

1 Answers1

1

Use var difference= Math.abs(firstDate - secondDate)

Oli Bates
  • 31
  • 5
  • I have "var diffDays = Math.abs((firstDate - secondDate)/(oneDay));" which successfully returns the difference in days, but it seems to make mistakes between months. Today is June the 30th and tomorrow is July the 1st, but it says that there's a two day difference between 06/30/2014 and 07/01/2014. – user3688016 Jun 30 '14 at 13:12