note 96768 added to dateinterval.format
| From: | baptiste dot place at utopiaweb dot fr | Date: | Mon, 15 Mar 2010 15:47:56 +0000 |
| Subject: | note 96768 added to dateinterval.format | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-167033@lists.php.net to get a copy of this message | ||
With php 5.3, DateTime is sweet !
Here is one quick example :
/**
* A sweet interval formatting, will use the two biggest interval parts.
* On small intervals, you get minutes and seconds.
* On big intervals, you get months and days.
* Only the two biggest parts are used.
*
* @param DateTime $start
* @param DateTime|null $end
* @return string
*/
public function formatDateDiff($start, $end=null) {
if(!($start instanceof DateTime)) {
$start = new DateTime($start);
}
if($end === null) {
$end = new DateTime();
}
if(!($end instanceof DateTime)) {
$end = new DateTime($start);
}
$interval = $end->diff($start);
$doPlural = function($nb,$str){return $nb>1?$str.'s':$str;}; // adds plurals
$format = array();
if($interval->y !== 0) {
$format[] = "%y ".$doPlural($interval->y, "year");
}
if($interval->m !== 0) {
$format[] = "%m ".$doPlural($interval->m, "month");
}
if($interval->d !== 0) {
$format[] = "%d ".$doPlural($interval->d, "day");
}
if($interval->h !== 0) {
$format[] = "%h ".$doPlural($interval->h, "hour");
}
if($interval->i !== 0) {
$format[] = "%i ".$doPlural($interval->i, "minute");
}
if($interval->s !== 0) {
if(!count($format)) {
return "less than a minute ago";
} else {
$format[] = "%s ".$doPlural($interval->s, "second");
}
}
// We use the two biggest parts
if(count($format) > 1) {
$format = array_shift($format)." and ".array_shift($format);
} else {
$format = array_pop($format);
}
// Prepend 'since ' or whatever you like
return $interval->format($format);
}
----
Server IP: 69.147.83.197
Probable Submitter: 85.170.209.162
----
Manual Page -- http://www.php.net/manual/en/dateinterval.format.php
Edit -- https://master.php.net/note/edit/96768
Del: integrated -- https://master.php.net/note/delete/96768/integrated
Del: useless -- https://master.php.net/note/delete/96768/useless
Del: bad code -- https://master.php.net/note/delete/96768/bad+code
Del: spam -- https://master.php.net/note/delete/96768/spam
Del: non-english -- https://master.php.net/note/delete/96768/non-english
Del: in docs -- https://master.php.net/note/delete/96768/in+docs
Del: other reasons-- https://master.php.net/note/delete/96768
Reject -- https://master.php.net/note/reject/96768
Search -- https://master.php.net/manage/user-notes.php