Skip to content

Instantly share code, notes, and snippets.

@abcarroll
Created July 14, 2019 05:44
Show Gist options
  • Save abcarroll/13b50edfdbace033b68aa2963e04552f to your computer and use it in GitHub Desktop.
Save abcarroll/13b50edfdbace033b68aa2963e04552f to your computer and use it in GitHub Desktop.
Simple "fuzzy" dateInterval string creation
<?php
namespace Tc\Std;
// Define these as descendands of \Exception or whaever
use Tc\Std\Exception\DateTimeInvalidArgument;
use Tc\Std\Exception\DateTimeUnexpectedResult;
abstract class DateTimeUtil
{
public static function getApproximateDifferenceString(\DateTimeInterval $interval, $taxonomies = 2, $largest = 'y', $smallest = 'i')
{
$word = [];
$convert = [
'y' => 'year/s', 'm' => 'month/s', 'd' => 'day/s', 'h' => 'hour/s', 'i' => 'minute/s', 's' => 'second/s'
];
$keys = array_keys($convert);
$largestPos = array_search($largest, $keys, true);
if($largestPos === null) {
throw new DateTimeInvalidArgument("Invalid argument largest value '$largest'. (Valid: " . implode(', ', $keys) . ")");
}
$smallestPos = array_search($smallest, $keys, true);
if($smallestPos === null) {
throw new DateTimeInvalidArgument("Invalid argument smallest value '$largest'. (Valid: " . implode(', ', $keys) . ")");
}
foreach ($interval as $q => $v) {
if ($v > 0) {
$suffix = $convert[$q];
$position = array_search($q, $keys, true);
if($position === null) {
throw new DateTimeUnexpectedResult("Unexpected identifier '$q' from interval diff.");
}
if ($position >= $largestPos && $position <= $smallestPos) {
list($suffixSingle, $suffixPlural) = explode('/', $suffix, 2);
$part = "$v $suffixSingle";
if ($v > 1) {
$part .= $suffixPlural;
}
$word[] = $part;
if (count($word) >= 2) break;
}
}
}
return implode($word, ', ');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment