-1

I need to calculate difference between two calendar dates. I have gone through various posts but the value returned is not correct. Heres' my code:-

    function getTotalDays()
{
    var date11 = document.getElementById("departure_date").value;
    var date22 = document.getElementById("arrival_date").value;

    var one_day=1000*60*60*24;

    var date1 = new Date(date11);
    var date2 = new Date(date22);

      // Convert both dates to milliseconds
      var date1_ms = date1.getTime();
      var date2_ms = date2.getTime();

      // Calculate the difference in milliseconds
      var difference_ms = date2_ms - date1_ms;

      // Convert back to days and return
      var diffDays =  Math.round(difference_ms/one_day); 
    alert(diffDays);


}

suppse the difference is 2 days its showing as 59. What's wrong..??

rams
  • 13
  • 2
  • 6
  • What does `difference_ms` output as? You are indicating it is somewhere in the region of 5,097,600,000ms. – James Coyle Apr 04 '13 at 10:34
  • You know you can do this? `date2 - date1`? No need for `getTime()`. – elclanrs Apr 04 '13 at 10:35
  • In what format are the strings `date11` and `date22`? Maybe they are parsed in a wrong way. – matthias.p Apr 04 '13 at 10:38
  • hey thnx for the replies @jimjimmy1995 the difference_ms for 1 day gives 2419200000 . – rams Apr 04 '13 at 10:39
  • @elclanrs hi even if i use date2-date1 its showing 30 days for 1 day. – rams Apr 04 '13 at 10:42
  • @matthias.p the dates are in the format of dd/mm/yyyy – rams Apr 04 '13 at 10:43
  • @rams Then there is the error, because the `Date` constructor accepts string values only as IETF-compliant RFC 2822 timestamps, e.g. `Thu, 01 Jan 1970`. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date – matthias.p Apr 04 '13 at 10:46
  • Possible duplicate of [Compare two dates with JavaScript](https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) –  Aug 02 '17 at 14:44

1 Answers1

0

The values you are passing to the date object are likely wrong. Its probably easier for you to do something like this:

var date1 = getDate(date11);
var date2 = getDate(date22);

with getDate being:

function getDate(date) {
    //date format dd/mm/yyyy
    var dateArr = date.split('/');
    var date = new Date(dateArr[2], dateArr[1], dateArr[0]);
    return date;
}
James Coyle
  • 9,922
  • 1
  • 40
  • 48