I am trying to find difference between two dates. It simple does not display anything , empty page shown for the date difference.
below is the code that i am using.
<?
$sql = $Db1->query("SELECT * FROM table LIMIT 5");
while($row = $Db1->fetch_array($sql)) {
$datetime1 = date("m-d-Y",mktime(0,0,$row['rec'],1,1,1970));
$datetime2 = date("m-d-Y",mktime(0,0,$row['send'],1,1,1970));
echo "$datetime1";
echo "$datetime2";
$diff=date_diff($datetime1,$datetime2);
echo $diff->format("%R%a days");
echo "$diff";
}
?>
use this function
$date1 = $row['rec'];
$date2 = $row['send'];
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
printf("%d years, %d months, %d days
", $years, $months, $days);
i have created a function that i use you can change it to as per your requirement. leave date two empty if you want to find difference b/w current date and given date.
function dayspassed($dategiven, $dategiven2){
if(empty($dategiven2)){
$currentdate = date('Y-m-d');
}else{
$currentdate = $dategiven2;
}
$currentdate = strtotime($currentdate);
$dategiven = explode(" ", $dategiven);
$dategiven = $dategiven['0'];
$yourdate = strtotime($dategiven);
$datediff = $yourdate - $currentdate;
return $difference = floor($datediff/(60*60*24));
}
I have the following function:
function get_date_difference_in_days($timestamp1, $timestamp2) {
$inputSeconds = abs($timestamp1 - $timestamp2);
$days = floor($inputSeconds / (24 * 60 * 60));
return $days;
}
The problem with your code is that date_diff works with datetime objects, and you were passing parameters as a string and not as datetime objects.
Looking at the docs clearly states that date_diff is an alias function for DateTime::diff().
So the solution would be:
$row = array("rec" => "2014-12-24", "send" => "2014-12-20");
$datetime1 = DateTime::createFromFormat("Y-m-d", $row["rec"]);
$datetime2 = DateTime::createFromFormat("Y-m-d", $row["send"]);
echo $datetime1->format("Y-m-d");
echo $datetime2->format("Y-m-d");
$diff = $datetime1->diff($datetime2);
echo $diff->format("%r%a");