note 101771 modified in function.date-diff by danbrown
| From: | danbrown@php.net | Date: | Tue, 11 Jan 2011 15:41:25 +0000 |
| Subject: | note 101771 modified in function.date-diff by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-175641@lists.php.net to get a copy of this message | ||
Here is how I solved the problem of missing date_diff function with php versions below 5.3.0
The function accepts two dates in string format (recognized by strtotime() hopefully), and returns
the date difference in an array with the years as first element, respectively months as second, and
days as last element.
It should be working in all cases, and seems to behave properly when moving through February.
<?php
function dateDifference($startDate, $endDate)
{
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
if ($startDate === false || $startDate < 0 || $endDate === false || $endDate < 0 ||
$startDate > $endDate)
return false;
$years = date('Y', $endDate) - date('Y', $startDate);
$endMonth = date('m', $endDate);
$startMonth = date('m', $startDate);
// Calculate months
$months = $endMonth - $startMonth;
if ($months <= 0) {
$months += 12;
$years--;
}
if ($years < 0)
return false;
// Calculate the days
$offsets = array();
if ($years > 0)
$offsets[] = $years . (($years == 1) ? ' year' : '
years');
if ($months > 0)
$offsets[] = $months . (($months == 1) ? ' month' : '
months');
$offsets = count($offsets) > 0 ? '+' . implode(' ',
$offsets) : 'now';
$days = $endDate - strtotime($offsets, $startDate);
$days = date('z', $days);
return array($years, $months, $days);
}
?>
--was--
Here is how I solved the problem of missing date_diff function with php versions below 5.3.0
The function accepts two dates in string format (recognized by strtotime() hopefully), and returns
the date difference in an array with the years as first element, respectively months as second, and
days as last element.
It should be working in all cases, and seems to behave properly when moving through February.
<?php
function dateDifference($startDate, $endDate)
{
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
if ($startDate === false || $startDate < 0 || $endDate === false || $endDate < 0 ||
$startDate > $endDate)
return false;
$years = date('Y', $endDate) - date('Y', $startDate);
$endMonth = date('m', $endDate);
$startMonth = date('m', $startDate);
// Calculate months
$months = $endMonth - $startMonth;
if ($months <= 0) {
$months += 12;
$years--;
}
if ($years < 0)
return false;
// Calculate the days
$measure = ($months == 1) ? 'month' : 'months';
$days = $endDate - strtotime('+' . $months . ' ' . $measure, $startDate);
$days = date('z', $days);
return array($years, $months, $days);
}
?>
http://php.net/manual/en/function.date-diff.php