Skip to content

Instantly share code, notes, and snippets.

@luads
Created April 12, 2013 20:59
Show Gist options
  • Save luads/5375091 to your computer and use it in GitHub Desktop.
Save luads/5375091 to your computer and use it in GitHub Desktop.
Extensão pro twig exibir quanto tempo passou entre uma data qualquer e a data atual
<?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