Skip to content

Instantly share code, notes, and snippets.

@davidkryzaniak
Created June 11, 2014 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidkryzaniak/0d5256f84be4f7985d1a to your computer and use it in GitHub Desktop.
Save davidkryzaniak/0d5256f84be4f7985d1a to your computer and use it in GitHub Desktop.
<?php
/**
* User: @davidkryzaniak
* Date: 6/10/14
* Time: 15:10
*/
class FuzzyDate{
private $SECOND = 1;
private $MINUTE = 60;
private $HOUR = 3600;
private $DAY = 86400;
private $MONTH = 259000;
private $YEAR = 946080000;
/**
* Make a fuzzy date message.
*
* @param int number of seconds between now and the event (likely a post or something)
* @return string like "6 minutes ago" or "last year"
*/
public function __construct($timeSince)
{
if ($timeSince <= 0){return "Just now";}
if ($timeSince < 1 * $this->MINUTE){return $timeSince == $this->SECOND ? "One second ago" : $timeSince . " seconds ago";}
if ($timeSince < 2 * $this->MINUTE){return "A minute ago";}
if ($timeSince < 45 * $this->MINUTE){return floor($timeSince/$this->MINUTE) . " minutes ago";}
if ($timeSince < 90 * $this->MINUTE){return "An hour ago";}
if ($timeSince < 24 * $this->HOUR){return floor($timeSince/$this->HOUR) . " hours ago";}
if ($timeSince < 48 * $this->HOUR){return "Yesterday";}
if ($timeSince < 30 * $this->DAY){return floor($timeSince/$this->DAY) . " days ago";}
if ($timeSince < 12 * $this->MONTH){
return $timeSince/$this->MONTH <= 1 ? "Last month" : floor($timeSince/$this->MONTH) . " months ago";
}else{
return $timeSince/$this->YEAR <= 1 ? "Last year" : floor($timeSince/$this->YEAR) . " years ago";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment