note 105257 added to function.time
| From: | dev dot ivangc at gmail dot com | Date: | Fri, 05 Aug 2011 10:05:52 +0000 |
| Subject: | note 105257 added to function.time | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-182247@lists.php.net to get a copy of this message | ||
Here a class extension to get the a datetime in the "X time ago" format easily.
<?php
class Cokidoo_DateTime extends DateTime {
protected $strings = array(
'y' => array('1 year ago', '%d years ago'),
'm' => array('1 month ago', '%d months ago'),
'd' => array('1 day ago', '%d days ago'),
'h' => array('1 hour ago', '%d hours ago'),
'i' => array('1 minute ago', '%d minutes ago'),
's' => array('now', '%d secons ago'),
);
/**
* Returns the difference from the current time in the format X time ago
* @return string
*/
public function __toString() {
$now = new DateTime('now');
$diff = $this->diff($now);
foreach($this->strings as $key => $value){
if( ($text = $this->getDiffText($key, $diff)) ){
return $text;
}
}
return '';
}
/**
* Try to construct the time diff text with the specified interval key
* @param string $intervalKey A value of: [y,m,d,h,i,s]
* @param DateInterval $diff
* @return string|null
*/
protected function getDiffText($intervalKey, $diff){
$pluralKey = 1;
$value = $diff->$intervalKey;
if($value > 0){
if($value < 2){
$pluralKey = 0;
}
return sprintf($this->strings[$intervalKey][$pluralKey], $value);
}
return null;
}
}
?>
How to use:
<?php
$date = new Cokidoo_Datetime('2011-01-01');
echo $date;
?>
----
Server IP: 69.147.83.197
Probable Submitter: 83.165.217.159
----
Manual Page -- http://www.php.net/manual/en/function.time.php
Edit -- https://master.php.net/note/edit/105257
Del: integrated -- https://master.php.net/note/delete/105257/integrated
Del: useless -- https://master.php.net/note/delete/105257/useless
Del: bad code -- https://master.php.net/note/delete/105257/bad+code
Del: spam -- https://master.php.net/note/delete/105257/spam
Del: non-english -- https://master.php.net/note/delete/105257/non-english
Del: in docs -- https://master.php.net/note/delete/105257/in+docs
Del: other reasons-- https://master.php.net/note/delete/105257
Reject -- https://master.php.net/note/reject/105257
Search -- https://master.php.net/manage/user-notes.php