Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Calculate the Difference between 2 dates

1. ## Calculate the Difference between 2 dates

Hello,

I'd like to be able to calculate the difference between 2 dates in the format dd/mm/yyyy

var date1 = 06/01/2012

var date2 = 10/01/2012

Then an alert box would tell me there is a difference of 4 days.

Thanks a bunch

Jay.

• Code:
```function get_time_difference(earlierDate,laterDate)  {
return Math.floor((laterDate.getTime() - earlierDate.getTime())/(1000*60*60*24));
}

date1 = new Date(2011, 05, 23, 02, 55, 0);
date2 = new Date(2011, 12, 06, 02, 55, 0);
alert("It has been " + get_time_difference(date1, date2) + " days");```
I chose 6th December 2011 and 23rd May 2011, but you can chose any dates you want, in date format not as a string

• To work in American (and some others places) you first have to fiddle with the input strings to get the correct dates.
Code:
```function dayfromDMY(s){
var A= s.split(/\D+/);
for(var i= 0, L= s.length; i<L; i++)A[i]= parseInt(A[i]);
A[1]-= 1;
return new Date(A[2], A[1], A[0])
}```

Code:
```var date1= '06/01/2012',
date2= '10/01/2012',
diff=dayfromDMY(date2)-dayfromDMY(date1);```

/* returned value: (Number)
4
*/

• My method using string values:-

Code:
```<script type = "text/javascript">

var date1="10/08/2011" ;  // DD/MM/YYYY  Note that strings must be enclosed in quotes
var date2="15/12/2012";

var one_day = 1000*60*60*24;
var x = date1.split("/");
var y = date2.split("/");
//date format(YYYY/MM/DD)
var date1 = new Date(x[2],(x[1]-1),x[0]);  // change for USA date format
var date2 = new Date(y[2],(y[1]-1),y[0])
var Diff = Math.ceil((date2.getTime() - date1.getTime())/(one_day));

</script>```

Quizmaster: What is the meaning of the French expression "sang froid"?
Contestant: A bloody cold.

• Wow....Thanks all.

This coding is like rocket science to me.

Great big thanks to everyone on this forum for helping me with this request.

You guys are the best.

Much thanks and appreciation.

Cheers, and have a great day!

Jay

• Originally Posted by jason_kelly
This coding is like rocket science to me.
So - did anyone dare tell George Stephenson, "It's not Rocket science"?

•