Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * RelativeTime - pretty printed
- *
- * @package Site5 Helpdesk
- * @author Dejan Marjanovic <dmarjanovic@site5.com>
- */
- class Site5_RelativeTime
- {
- private $interval = '';
- public function __construct()
- {
- call_user_func_array(array(__CLASS__, 'calculate'), func_get_args());
- }
- public function calculate($start, $end = NULL)
- {
- if ( empty($start))
- return false;
- if (empty($end))
- $end = time();
- if ( ! is_numeric($start))
- $start = strtotime($start);
- if ( ! is_numeric($end))
- $end = strtotime($end);
- if($start > $end)
- $future = TRUE;
- $start = '@' . $start;
- $end = '@' . $end;
- if ( ! ($start instanceof DateTime))
- $start = new DateTime($start);
- if ($end === null)
- $end = new DateTime();
- if ( ! ($end instanceof DateTime))
- $end = new DateTime($end);
- $interval = $end->diff($start);
- $get_plural = function($int, $str)
- {
- return $int > 1? $str.'s': $str;
- };
- $format = array();
- if ($interval->y !== 0)
- $format[] = "%y " . $get_plural($interval->y, "year");
- if ($interval->m !== 0)
- $format[] = "%m " . $get_plural($interval->m, "month");
- if ($interval->d !== 0)
- $format[] = "%d " . $get_plural($interval->d, "day");
- if ($interval->h !== 0)
- $format[] = "%h " . $get_plural($interval->h, "hour");
- if ($interval->i !== 0)
- $format[] = "%i " . $get_plural($interval->i, "minute");
- if ($interval->s !== 0)
- {
- if ( ! count($format))
- {
- $this->interval = "less than a minute";
- return;
- }
- else
- {
- $format[] = "%s " . $get_plural($interval->s, "second");
- }
- }
- if (count($format) > 1)
- {
- $format = array_shift($format) . " and " . array_shift($format);
- }
- else
- {
- $format = array_pop($format);
- }
- $tense = ($future === TRUE)? 'from now': 'ago';
- $this->interval = $interval->format($format) . ' ' . $tense;
- }
- public function __toString()
- {
- return $this->interval;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement