Skip to content

Instantly share code, notes, and snippets.

@duboiss
Created November 2, 2020 16:51
Show Gist options
  • Save duboiss/f8a2d60cea1fc3d160994f27f7071c4f to your computer and use it in GitHub Desktop.
Save duboiss/f8a2d60cea1fc3d160994f27f7071c4f to your computer and use it in GitHub Desktop.
Twig DateInterval format filter
<?php
declare(strict_types=1);
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class DateExtension extends AbstractExtension
{
public function getFilters(): array
{
return [
new TwigFilter('dateIntervalFormat', [$this, 'dateIntervalFormat']),
];
}
public function dateIntervalFormat(\DateInterval $dateInterval): string
{
$months = (int) $dateInterval->format('%m');
$days = (int) $dateInterval->format('%d');
$hours = (int) $dateInterval->format('%H');
return trim($this->format($months, 'Month').$this->format($days, 'Day').$this->format($hours, 'Hour'));
}
private function format(int $period, string $stringPeriod): string
{
return $period ? sprintf('%d %s%s ', $period, $stringPeriod, $period > 1 ? 's' : '') : '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment