-2

I have 2 <input type="text"> tags and I enter dates in them like this 22-05-2013

I want to subtract 22-06-2012 from that date

How do I do this?

I've tried this code but it didn't work:

function returnDate(nDays){
  var now = new Date();
  var dayOfTheWeek = now.getDay();
  now.setTime(now.getTime() - nDays * 24 * 60 * 60 * 1000);

  alert(now);  // returns current date
  alert(now.getFullYear() + "/"+(now.getMonth()+1)+"/"+now.getDate()) // returns new calculated date
}

So I need the difference between 22-05-2013 and 22-06-2012

Floris
  • 653
  • 4
  • 10
zamalek 100
  • 55
  • 2
  • 8
  • Duplicate. http://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript/15289883#15289883 – kol Aug 28 '13 at 14:49
  • And of http://stackoverflow.com/questions/4944750/how-to-subtract-date-time-in-javascript, which is also a duplicate. Search before asking. – Virus721 Aug 28 '13 at 14:49

3 Answers3

2

The best way to do it would be to use Moment.js. It has fantastic support for dates.

Jason
  • 13,563
  • 15
  • 74
  • 125
0

In javascript you could subtract 2 Date objects and this will return the number of milliseconds between them. For example:

var date1 = new Date('2013-06-22 01:00:00');
var date2 = new Date('2013-06-22 01:00:01');

var result = date2 - date1;
alert(result); // shows 1000 which is 1 second
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

Simple:

new Date(mydate1 - mydate2).getDay() ;

This will give you the number of days.

I would suggest you use Date.js though, which would be even simpler.

Imad Alazani
  • 6,688
  • 7
  • 36
  • 58
j7m
  • 1,067
  • 8
  • 13