Created
November 2, 2020 16:51
-
-
Save duboiss/f8a2d60cea1fc3d160994f27f7071c4f to your computer and use it in GitHub Desktop.
Twig DateInterval format filter
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 | |
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