...

# Calculate the Difference between 2 dates

jason_kelly
01-10-2012, 09:44 PM
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.

nomanic
01-10-2012, 10:23 PM
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

mrhoo
01-10-2012, 10:30 PM
To work in American (and some others places) you first have to fiddle with the input strings to get the correct dates.

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])
}

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

/* returned value: (Number)
4
*/

Philip M
01-11-2012, 10:02 AM
My method using string values:-

<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));
alert (Diff + " days");

</script>

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

jason_kelly
01-11-2012, 05:06 PM
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

Philip M
01-11-2012, 06:02 PM
This coding is like rocket science to me.

So - did anyone dare tell George Stephenson, "It's not Rocket science"?

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum