Page 1 of 1
count the days between 2 date fields.
Posted: Sat Oct 29, 2011 6:33 am
by jauson
Hi, I am looking all over the internet for a days but Im getting a hard time to find the best tutorial for counting the days for 2 different date fields. I was looking for live counting, I mean for example. I have 3 fields.
datefrom: 1/12/2011
dateto: 1/14/2011
total days: 2 days (readonly)
when the user set the date_from and date_to, total_days field will automatically count when 2 fields are set. is it possible in php? any suggestion or link will be appreciated.

thanks guys
Re: count the days between 2 date fields.
Posted: Sat Oct 29, 2011 9:06 am
by Celauran
Code: Select all
$date1 = strtotime($date1);
$date2 = strtotime($date2);
$diff = ($date2 - $date1) / (24 * 60 * 60);
echo $diff;
Re: count the days between 2 date fields.
Posted: Sun Oct 30, 2011 4:06 am
by dsnraju
Code: Select all
<?php
$days = (strtotime("2011-10-30") - strtotime("2005-11-20")) / (60 * 60 * 24);
print $days;
?>
Re: count the days between 2 date fields.
Posted: Sun Oct 30, 2011 11:11 pm
by Gopesh
Hi,U can do this dynamically with php and ajax.It can also be done with javascript Ex:
Code: Select all
<?php
<form>
<input type="text" name="textFromDate" id="textFromDate" />
<input type="text" name="textToDate" id="textToDate" onchange="getdate()"/>
<input type="text" name="textTotalDays" id="textTotalDays" readonly="readonly" />
<input type="submit" name="buttonApply" id="buttonApply" value="Apply Leave" />
</form>
?>
Function getdate() is :
Code: Select all
function getdate()
{
var one_day=1000*60*60*24;
var fdate = document.getElementById("textFromDate").value;
var tdate = document.getElementById("textToDate").value;
var date1=new Date(fdate);
var date2=new Date(tdate);
if(date1>date2)
{
alert("Not possible");
}
else{
//Calculate difference between the two dates, and convert to days
var Diff=Math.ceil((date2.getTime()-date1.getTime())/one_day);
document.getElementById("textTotalDays").value=Diff+1;
}
}
Hope it will be useful to u..
[Sorry for posting javascript code here]
Re: count the days between 2 date fields.
Posted: Tue Nov 01, 2011 7:11 pm
by jauson
Hi thanks Gopesh,
I found that the total_days for dateFrom and dateTo is wrong. the value is advance of 1 day always/
Re: count the days between 2 date fields.
Posted: Wed Nov 02, 2011 11:25 pm
by Gopesh
Have u run that code? what is the result ??. if the result is wrong,rework on that piece of code.i just give u an example for dynamically populating values to the textbox .
Re: count the days between 2 date fields.
Posted: Thu Nov 03, 2011 7:53 am
by jauson
thank you Gopesh for a wonderful tutorial. I just run the code and it works perpectly. sorry for my previous comment.
Re: count the days between 2 date fields.
Posted: Thu Nov 03, 2011 3:39 pm
by pickle
Be sure to floor() the result, as twice a year the number won't be exact due to Daylight Saving Time shifts.