Days Ago Twig Filter

Here is a twig filter that converts a datetime object into minutes ago/days ago. Props to headzoo for the hard part.

<?php
namespace Application\CommentBundle\Twig;

class CommentExtension extends \Twig_Extension {

    public function getFilters()
    {
        return array(
            'daysAgo'    => new \Twig_Filter_Function(
                '\Application\CommentBundle\Twig\CommentExtension::daysAgoFilter'
            )
        );
    }

    public function getName()
    {
        return 'CommentExtension';
    }

    public static function daysAgoFilter($date)
    {
        $display = array('Year', 'Month', 'Day', 'Hour', 'Minute', 'Second');
        $ago = 'Ago';

        $date = getdate($date->getTimestamp());
        $current = getdate();
        $p = array('year', 'mon', 'mday', 'hours', 'minutes', 'seconds');
        $factor = array(0, 12, 30, 24, 60, 60);

        for ($i = 0; $i < 6; $i++) {
            if ($i > 0) {
                $current[$p[$i]] += $current[$p[$i - 1]] * $factor[$i];
                $date[$p[$i]] += $date[$p[$i - 1]] * $factor[$i];
            }
            if ($current[$p[$i]] - $date[$p[$i]] > 1) {
                $value = $current[$p[$i]] - $date[$p[$i]];
                return $value . ' ' . $display[$i] . (($value != 1) ? 's' : '') . ' ' . $ago;
            }
        }

        return 'just now';
    }
}

And of course, load the extension in your config

services:
    comment.twig.extension:
        class: Application\CommentBundle\Twig\CommentExtension
        tags:
            -  { name: twig.extension }

Leave a Reply

Your email address will not be published.