ProAnswers.org

How do you compute the difference in days between two dates formatted as yyyy-mm-dd in PHP?

How do you compute the difference in days between two dates formatted as yyyy-mm-dd in PHP?

A simple Logic may be as

function dayDiff($date1, $date2)

{

if($date1 < $date 2)

{
$dateStart = $date1;
$dateEnd = $date2;
}
else
{
$dateStart = $date2;
$dateEnd = $date1;
}

$date1Timestamp = strtotime($dateStart );

$date2Timestamp = strtotime($dateEnd );

$dayDiff = ($date2Timestamp - $date1Timestamp)/(606024);

return $dayDiff;
}
No matter in which format dates are formatted.

Answer

/**

  • Returns the number of days between two PHP dates
    */
    function days_between($d1, $d2){
    if($d1 >= $d2){
    $dd1 = $d2;
    $dd2 = $d1;
    }
    else{
    $dd1 = $d1;
    $dd2 = $d2;
    }
    return floor(($dd2 - $dd1) / 86400);
    }

/**

  • Converts an ISO 8601 YYYY-MM-DD date to a PHP date
    */
    function iso_date_to_timestamp($dt){
    list($y, $m, $d) = explode("-", $dt, 3);
    if(is_numeric($y) && is_numeric($m) && is_numeric($d)){
    return mktime(0, 0, 0, intval($m), intval($d), intval($y));
    }
    else{
    return 0;
    }
    }

/**

  • Returns the number of days between two dates expressed as ISO8601
  • style YYYY-MM-DD dates
    */
    function days_between_iso($d1, $d2){
    return days_between(iso_date_to_timestamp($d1), iso_date_to_timestamp($d2));
    }