Skip to content

Instantly share code, notes, and snippets.

@odirleiborgert
Forked from luads/DateSinceExtension.php
Created September 4, 2013 18:17
Show Gist options
  • Save odirleiborgert/6440720 to your computer and use it in GitHub Desktop.
Save odirleiborgert/6440720 to your computer and use it in GitHub Desktop.
<?php
namespace Acme\CoreBundle\Twig;
class DateSinceExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
'date_since' => new \Twig_Filter_Method($this, 'dateSince'),
);
}
public function dateSince($date)
{
$date = ($date instanceof \DateTime) ? $date->getTimestamp() : strtotime($date);
$since = time() - $date;
// time, singular, plural
$periods = array(
array(60 * 60 * 24 * 365 , 'ano', 'anos'),
array(60 * 60 * 24 * 30 , 'mês', 'meses'),
array(60 * 60 * 24 * 7, 'semana', 'semanas'),
array(60 * 60 * 24 , 'dia', 'dias'),
array(60 * 60 , 'hora', 'horas'),
array(60 , 'minuto', 'minutos'),
array(1 , 'segundo', 'segundos'),
);
foreach ($periods as $period) {
if ($since < $period[0]) {
continue;
}
$numberOfUnits = floor($since / $period[0]);
return $numberOfUnits .' '. (($numberOfUnits > 1) ? $period[2] : $period[1]);
}
return 'agora';
}
public function getName()
{
return 'date_since_extension';
}
}
services:
acme.twig.date_since_extension:
class: Acme\CoreBundle\Twig\DateSinceExtension
tags:
- { name: twig.extension }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment