Created
April 25, 2014 10:24
-
-
Save defrag/11284749 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class DistanceOfTimeInWords | |
{ | |
const MINUTES_IN_YEAR = 525600; | |
const MINUTES_IN_QUARTER_YEAR = 131400; | |
const MINUTES_IN_THREE_QUARTERS_YEAR = 394200; | |
const UP_TO_24_HOURS = 1440; | |
const UP_TO_48_HOURS = 2520; | |
const UP_TO_30_DAYS = 43200; | |
const UP_TO_60_DAYS = 86400; | |
const UP_TO_365_DAYS = 525600; | |
/** | |
* @var \DateTime | |
*/ | |
private $fromTime; | |
/** | |
* @var \DateTime | |
*/ | |
private $toTime; | |
public function __construct(\DateTime $fromTime, \DateTime $toTime) | |
{ | |
$this->fromTime = $fromTime; | |
$this->toTime = $toTime; | |
} | |
public function __toString() | |
{ | |
$fromTs = $this->fromTime->getTimestamp(); | |
$toTs = $this->toTime->getTimestamp(); | |
$distanceInMinutes = round(($toTs - $fromTs) / 60.0); | |
if ($distanceInMinutes <= 1) { | |
return "less than a minute"; | |
} elseif ($distanceInMinutes <= 45) { | |
return sprintf("%s minutes", $distanceInMinutes); | |
} elseif ($distanceInMinutes <= 90) { | |
return "about 1 hour"; | |
} elseif ($distanceInMinutes <= self::UP_TO_24_HOURS) { | |
return sprintf("about %s hours", round($distanceInMinutes / 60.0)); | |
} elseif ($distanceInMinutes <= self::UP_TO_48_HOURS) { | |
return "about 1 day"; | |
} elseif ($distanceInMinutes <= self::UP_TO_30_DAYS) { | |
return sprintf("about %s days", round($distanceInMinutes / 1440.0)); | |
} elseif ($distanceInMinutes <= self::UP_TO_60_DAYS) { | |
return sprintf("about %s months", round($distanceInMinutes / 43200.0)); | |
} elseif ($distanceInMinutes <= self::UP_TO_365_DAYS) { | |
return sprintf("%s months", round($distanceInMinutes / 43200.0)); | |
} else { | |
$remainder = $distanceInMinutes % self::MINUTES_IN_YEAR; | |
$distanceInYears = floor($distanceInMinutes / self::MINUTES_IN_YEAR); | |
if ($remainder < self::MINUTES_IN_QUARTER_YEAR) { | |
return sprintf("about %s years", $distanceInYears); | |
} elseif ($remainder < self::MINUTES_IN_THREE_QUARTERS_YEAR) { | |
return sprintf("over %s years", $distanceInYears); | |
} else { | |
return sprintf("almost %s years", $distanceInYears + 2); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment