Pico icon indicating copy to clipboard operation
Pico copied to clipboard

Nice Date filter

Open digitalinferno opened this issue 2 years ago • 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.

digitalinferno avatar Feb 15 '24 21:02 digitalinferno

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

PhrozenByte avatar Feb 15 '24 21:02 PhrozenByte

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

digitalinferno avatar Feb 16 '24 11:02 digitalinferno

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! :+1:

github-actions[bot] avatar Feb 23 '24 12:02 github-actions[bot]