note 98728 added to function.date-diff
| From: | equipo at anavallasuiza dot com | Date: | Fri, 02 Jul 2010 17:17:18 +0000 |
| Subject: | note 98728 added to function.date-diff | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-170667@lists.php.net to get a copy of this message | ||
This is my dateDiff function:
<?php
/**
* function dateDiff (string $date1, string $date2, string $format)
*
* Return dates differnce in format given
*
* Valid formats: m => minutes, h => hours, d => days, m => months, y => years
* return string
*/
function dateDiff ($date1, $date2, $format = 'md') {
$time1 = is_int($date1)?$date1:strtotime($date1);
$time2 = is_int($date2)?$date2:strtotime($date2);
if (!$time1 || !$time2) {
return false;
}
if ($time1 > $time2) {
list($time1, $time2) = explode(' ', $time2.' '.$time1);
}
$difference = $time2 - $time1;
$len = strlen($format);
$each = array();
for ($i = 0; $i < $len; $i++) {
switch ($format[$i]) {
case 'i':
$mult = 60;
$name = array(__('minute'), __('minutes'));
break;
case 'h':
$mult = (60 * 60);
$name = array(__('hour'), __('hours'));
break;
case 'd':
$mult = (60 * 60 * 24);
$name = array(__('day'), __('days'));
break;
case 'm':
$mult = (60 * 60 * 24 * 30);
$name = array(__('month'), __('months'));
break;
case 'y':
$mult = (60 * 60 * 24 * 30 * 12);
$name = array(__('year'), __('years'));
break;
default:
$mult = 0;
$name = array(__('second'), __('seconds'));
break;
}
if ($mult > 0) {
$value = intval($difference / $mult);
$difference = $difference - ($value * $mult);
} else {
$value = $difference;
$difference = 0;
}
if ($value > 0) {
if ($value == 1) {
$each[] = $value.' '.$name[0];
} else {
$each[] = $value.' '.$name[1];
}
}
}
return preg_replace('/,([^,]+)$/', ' '.__('and').' $1',
implode(', ', $each));
}
// Example:
echo dateDiff(time(), '2011-08-06', 'ymd');
// Return 1 year, 1 month and 9 days
echo dateDiff(time(), '2011-08-06', 'yd');
// Return 1 year and 39 days
echo dateDiff(time(), '2011-08-06', 'md');
// Return 13 months and 9 days
?>
----
Server IP: 69.147.83.197
Probable Submitter: 77.27.50.215
----
Manual Page -- http://www.php.net/manual/en/function.date-diff.php
Edit -- https://master.php.net/note/edit/98728
Del: integrated -- https://master.php.net/note/delete/98728/integrated
Del: useless -- https://master.php.net/note/delete/98728/useless
Del: bad code -- https://master.php.net/note/delete/98728/bad+code
Del: spam -- https://master.php.net/note/delete/98728/spam
Del: non-english -- https://master.php.net/note/delete/98728/non-english
Del: in docs -- https://master.php.net/note/delete/98728/in+docs
Del: other reasons-- https://master.php.net/note/delete/98728
Reject -- https://master.php.net/note/reject/98728
Search -- https://master.php.net/manage/user-notes.php