Calculate Date Difference

How will you calculate difference of two dates using PHP?

Questions by rubin2008   answers by rubin2008

Showing Answers 1 - 6 of 6 Answers

<?php

/********** Date Difference **************************/
function date_diff($d1, $d2){
  if ($d1 < $d2){
    $temp = $d2;
    $d2 = $d1;
    $d1 = $temp;
  }
  else {
    $temp = $d1; //temp can be used for day count if required
  }
  $d1 = date_parse(date("Y-m-d H:i:s",$d1)); // date_parse give complete details in array
  $d2 = date_parse(date("Y-m-d H:i:s",$d2));
  //seconds
  if ($d1['second'] >= $d2['second']){
    $diff['second'] = $d1['second'] - $d2['second'];
  }
  else {
    $d1['minute']--;
    $diff['second'] = 60-$d2['second']+$d1['second'];
  }
  //minutes
  if ($d1['minute'] >= $d2['minute']){
    $diff['minute'] = $d1['minute'] - $d2['minute'];
  }
  else {
    $d1['hour']--;
    $diff['minute'] = 60-$d2['minute']+$d1['minute'];
  }
  //hours
  if ($d1['hour'] >= $d2['hour']){
    $diff['hour'] = $d1['hour'] - $d2['hour'];
  }
  else {
    $d1['day']--;
    $diff['hour'] = 24-$d2['hour']+$d1['hour'];
  }
  //days
  if ($d1['day'] >= $d2['day']){
   echo  $diff['day'] = $d1['day'] - $d2['day'];
  }
  else {
    $d1['month']--;
    $diff['day'] = date("t",$temp)-$d2['day']+$d1['day'];  //date("t",$temp) gives no of days in that month
  }
  //months
  if ($d1['month'] >= $d2['month']){
    $diff['month'] = $d1['month'] - $d2['month'];
  }
  else {
    $d1['year']--;
    $diff['month'] = 12-$d2['month']+$d1['month'];
  }
  //years
  $diff['year'] = $d1['year'] - $d2['year'];
  return $diff;   
}

$born_date = mktime(24,24,24,11,12,2009); // hour min sec month day year
$up_date = mktime(24,24,24,12,11,2010);
$date_diff_array = date_diff($born_date, $up_date);
print_r($date_diff_array);
?>

  Was this answer useful?  Yes

Qambar

  • Jan 28th, 2010
 

// Calculate difference and returns the difference in days.
function bozimsDateDiff($date1, $date2)
{
 return floor(($date2 - $date1) / (3600 * 24));
}


// Usage
$date2 = time(); // e,g Date 2 CURRENT DATE TIMESTAMP
$date1 = mktime(0,0,0,1,17,1988); // e,g Date 1 My Birthday date timestamp
 
//diff in days
$days = bozimsDateDiff($date1, $date2);
//diff in hours
$hours = $days*24;
//diff in minutes
$minutes = $hours * 60;

//Display
echo "Days : " . $days;
echo "<br>";
echo "Hours : " . $hours;
echo "<br>";
echo "Minutes : " . $minutes;

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions