3

I am having two dated in dd/mm/yyyy format. How to calculate the number of days between these two dates in javascript/jquery.

Example: Fom date is 20/06/2000, to date is 16/08/2011

vinothini
  • 2,606
  • 4
  • 27
  • 42
  • 2
    possible duplicate: http://stackoverflow.com/questions/327429/whats-the-best-way-to-calculate-date-difference-in-javascript – LeeR Aug 16 '11 at 08:27
  • 2
    See http://stackoverflow.com/questions/1410285/calculating-the-difference-between-two-dates – Reporter Aug 16 '11 at 08:27
  • 1
    @vinothini You will need to accept more answers before asking any more questions. – Ariel Aug 16 '11 at 08:28
  • See related section of this question page. You will find similar questions. – Harry Joy Aug 16 '11 at 08:29

3 Answers3

9

Simple code

var Date1 = new Date (2008, 7, 25);
var Date2 = new Date (2009, 0, 12);
var Days = Math.round((Date2.getTime() - Date1.getTime())/(1000*60*60*24));
Chris
  • 473
  • 5
  • 18
Nightw0rk
  • 411
  • 3
  • 9
  • This fails when crossing from non-daylight savings time to daylight savings time. It will end up being one day less than it should be. The calculation (Date2.getTime() - Date1.... comes up to be (for example) 5.96, which using Math.floor becomes 5, when it should be 6. – Chris Mar 11 '23 at 02:49
  • Use Math.round instead. See another stackoverflow answer: https://stackoverflow.com/a/2627493/12942220 – Chris Mar 11 '23 at 03:07
3
t1="10/10/2006";
t2="15/10/2006";

//Total time for one day
var one_day=1000*60*60*24;  //Here we need to split the inputed dates to convert them into standard format for further execution
var x=t1.split("/");     
var y=t2.split("/");   //date format(Fullyear,month,date) 

var date1=new Date(x[2],(x[1]-1),x[0]);

// it is not coded by me,but it works correctly,it may be useful to all

var date2=new Date(y[2],(y[1]-1),y[0])
var month1=x[1]-1;
var month2=y[1]-1;

//Calculate difference between the two dates, and convert to days

_Diff=Math.ceil((date2.getTime()-date1.getTime())/(one_day));
vp_arth
  • 14,461
  • 4
  • 37
  • 66
Lachu
  • 31
  • 1
3
var date1 = new Date(2000, 6, 20);
var date2 = new Date(2011, 8, 16);

var one_day = 1000*60*60*24; //Get 1 day in milliseconds

var days = Math.ceil( (date2.getTime() - date1.getTime() ) / one_day);

Math.ceil to round up, Math.floor to round down.

http://www.javascriptkit.com/javatutors/datedifference.shtml

472084
  • 17,666
  • 10
  • 63
  • 81