1

How to calculate the difference between two dates say date 1 is 28-04-2014 and date 2 is 30-04-2014 how to find the difference using javascript .

Jay
  • 1,317
  • 4
  • 16
  • 40
user13763
  • 83
  • 7
  • 1
    You could check out the library [moment.js](http://momentjs.com/), it has many built-in operations to work on dates, including difference. – Barnabé Monnot Apr 28 '14 at 11:34
  • One of the many advantages with using ISO dates is that you can easily compare them (2014-04-28 < 2014-04-30). Where do you get the date from? Can you ask for them in a standard format? – leo Apr 28 '14 at 11:34
  • i get the date from a datepicker in front end – user13763 Apr 28 '14 at 11:35
  • Why reference a question that has a poor accepted answer? – RobG Apr 28 '14 at 12:12

2 Answers2

1

If you are using the datepicker from jQuery UI (or probably any other datepicker tool out there), you can chose what date format you want to recieve. In jQuery UI, use $( "#datepicker" ).datepicker( "option", "dateFormat", "yy-mm-dd" ); to get ISO 8601 dates, and then just compare them like this:

if ( dateOne < dateTwo ) ...

By using a standardized date format, you also know for sure that you will always be able to painlessly convert it to what ever format you want to display it in later.

leo
  • 8,106
  • 7
  • 48
  • 80
1

Vishwas' answer was actually pretty close, even though it's getting downvoted. You need to pass in a valid date format into the new Date() constructor.

var date1 = new Date("28-04-2014".split("-").reverse());
var date2 = new Date("30-04-2014".split("-").reverse());
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
console.log(diffDays, "number of days difference");
console.log(timeDiff, "in milliseconds");

The Date constructor needs dates in the form new Date(year, month, day, hour, minute etc etc..) and takes arrays too.

Since your date format is in the form day-month-year we take your string and split it (by -) and reverse it to get [year, month, day]

Full Date Object Reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Arjun Mehta
  • 2,500
  • 1
  • 24
  • 40