This DateInterval extension allows you to write a formatted timestamp but omit the "zero values" and handle things like listing, plurals, etc.
Example input: '%y year(s)', '%m month(s)', '%d day(s)', '%h hour(s)', '%i minute(s)', '%s second(s)'
Example output: 1 year, 2 months, 16 days, 1 minute, and 15 seconds
Example input: '%y año(s)', '%m mes(es)', '%d día(s)', '%h hora(s)', '%i minuto(s)', '%s segundo(s)'
Example output: 1 año, 2 meses, 16 días, 1 minuto, y 15 segundos
<meta charset="UTF-8">
<?php
error_reporting(E_ALL);
class MyDateInterval extends DateInterval {
public
$pluralCheck = '()',
$singularReplacement = '',
$separator = ', ',
$finalSeparator = ', and ',
$finalSeparator2 = ' and ';
public static function createFromDateInterval (DateInterval $interval) {
$obj = new self('PT0S');
foreach ($interval as $property => $value) {
$obj->$property = $value;
}
return $obj;
}
public function formatWithoutZeroes () {
$parts = array ();
foreach (func_get_args() as $arg) {
$pre = mb_substr($arg, 0, mb_strpos($arg, '%'));
$param = mb_substr($arg, mb_strpos($arg, '%'), 2);
$post = mb_substr($arg, mb_strpos($arg, $param)+mb_strlen($param));
$num = intval(parent::format($param));
$open = preg_quote($this->pluralCheck[0], '/');
$close = preg_quote($this->pluralCheck[1], '/');
$pattern = "/$open(.*)$close/";
list ($pre, $post) = preg_replace($pattern, $num == 1 ? $this->singularReplacement : '$1', array ($pre, $post));
if ($num != 0) {
$parts[] = $pre.$num.$post;
}
}
$output = '';
$l = count($parts);
foreach ($parts as $i => $part) {
$output .= $part.($i < $l-2 ? $this->separator : ($l == 2 ? $this->finalSeparator2 : ($i == $l-2 ? $this->finalSeparator : '')));
}
return $output;
}
}
date_default_timezone_set('America/Phoenix');
$today = new DateTime('today');
echo 'Today is ', $today->format('F d, Y h:ia'), '.<br>', PHP_EOL;
$expiration = new DateTime('today +1 year +2 months +16 days +1 minute +15 seconds');
echo 'Expires ', $expiration->format('F d, Y h:ia'), '.<br>', PHP_EOL;
$interval = MyDateInterval::createFromDateInterval($today->diff($expiration));
echo 'That is ', $interval->formatWithoutZeroes('%y year(s)', '%m month(s)', '%d day(s)', '%h hour(s)', '%i minute(s)', '%s second(s)'), ' from now.<br>', PHP_EOL;
$interval->finalSeparator = ', y ';
$interval->finalSeparator2 = ' y ';
echo 'Que es de ', $interval->formatWithoutZeroes('%y año(s)', '%m mes(es)', '%d día(s)', '%h hora(s)', '%i minuto(s)', '%s segundo(s)'), ' a partir de ahora.';
?>