HumanReadableTime.inc 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. class HumanReadableTime {
  3. private $tokens;
  4. private $time;
  5. public function __construct() {
  6. $this->tokens = array (
  7. 31536000 => 'year',
  8. 2592000 => 'month',
  9. 604800 => 'week',
  10. 86400 => 'day',
  11. 3600 => 'hour',
  12. 60 => 'minute',
  13. 1 => 'second'
  14. );
  15. $this->time = new Time();
  16. }
  17. public function formatString($timestampString) {
  18. $timeDifference = $this->time->now() - strtotime($timestampString);
  19. if ($timeDifference > 0) {
  20. return $this->getLargestUnit($timeDifference, "ago");
  21. } else if ($timeDifference < 0){
  22. $timeDifference = abs($timeDifference);
  23. return $this->getLargestUnit($timeDifference, "in the future");
  24. } else {
  25. return "now";
  26. }
  27. }
  28. private function getLargestUnit($timeDifference, $postfixString) {
  29. foreach ($this->tokens as $unit => $text) {
  30. if ($timeDifference >= $unit) {
  31. $numberOfUnits = floor($timeDifference / $unit);
  32. return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'') . ' ' . $postfixString;
  33. }
  34. }
  35. }
  36. }