Last active
August 14, 2016 14:19
-
-
Save mylk/ad7346a28220c7215019c6301f862d71 to your computer and use it in GitHub Desktop.
Twig filter that converts a datetime string to an "ago format", like "posted 9 months ago"
This file contains 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 | |
/* | |
* Installation: | |
* ============= | |
* # services.yml | |
* services: | |
* # ... | |
* acme.twig.time_ago: | |
* class: Acme\AcmeBundle\Twig\TimeAgoExtension | |
* tags: | |
* - { name: twig.extension } | |
* | |
* Usage: | |
* ====== | |
* {{ customer.birthday | date("Y-m-d H:i:s") | timeAgo }} | |
*/ | |
namespace Acme\AcmeBundle\Twig; | |
class TimeAgoExtension extends \Twig_Extension | |
{ | |
public function getFilters() | |
{ | |
return array( | |
new \Twig_SimpleFilter("timeAgo", array($this, "timeAgo")) | |
); | |
} | |
public function timeAgo($dateTime) | |
{ | |
$now = new \DateTime(); | |
$ago = new \DateTime($dateTime); | |
$diff = $now->diff($ago); | |
$diff->w = \floor($diff->d / 7); | |
$diff->d -= $diff->w * 7; | |
$periods = array( | |
"y" => "year", | |
"m" => "month", | |
"w" => "week", | |
"d" => "day", | |
"h" => "hour", | |
"i" => "minute", | |
"s" => "second" | |
); | |
foreach ($periods as $code => &$name) { | |
if ($diff->$code) { | |
$name = $diff->$code . " " . $name . ($diff->$code > 1 ? "s" : ""); | |
} else { | |
unset($periods[$code]); | |
} | |
} | |
// get only the most generic. Ex. from: | |
// array("9 months", "4 weeks", "2 days", "21 hours", "27 minutes", "37 seconds") | |
// return only array("9 months") | |
$difference = \array_slice($periods, 0, 1); | |
return $difference ? \implode(", ", $periods) . " ago" : "just now"; | |
} | |
public function getName() | |
{ | |
return "timeAgo_extension"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment