picocms/Pico

Nice Date filter

digitalinferno opened this issue · 3 comments

Just another adventure in the Pico Plugin system.

This time a filter for display a timestamp in time ago format:

  • just now
  • 4 minute ago
  • 6 days ago
  • 2 months ago
  • etc

The filter work like others twig filters: {{ meta.date|nice }}

<?php

class PicoNiceDate extends AbstractPicoPlugin
{
    const API_VERSION = 3;
    protected $enabled = true;
    protected $dependsOn = array();
     
    public function onTwigRegistered(Twig_Environment &$twig)
    {
        $twig->addFilter(new Twig_SimpleFilter('nice', function($timestamp) {
            return $this->convertDate($timestamp);
        }));
    }
    
    private function convertDate($timestamp)
    {
        if (strtotime($timestamp) !== false) {
            $originalDate = new DateTime($timestamp);
            $currentDate = new DateTime();
            $diff = $originalDate->diff($currentDate);
            return $this->humanize($diff);
        } else {
        return $timestamp;
        }
    }

    private function humanize(DateInterval $diff)
    {
    ...
    }
}

I just need to refine the 'humanize' function and it's ready.

There should be libraries out there dealing with stuff like this.

Sure, but I prefer something customizable according to my needs. Otherwise, does everything seem okay to you?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed in two days if no further activity occurs. Thank you for your contributions! 👍