Skip to content

Instantly share code, notes, and snippets.

@defrag
Created April 25, 2014 10:24
Show Gist options
  • Save defrag/11284749 to your computer and use it in GitHub Desktop.
Save defrag/11284749 to your computer and use it in GitHub Desktop.
<?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