picocms / Pico

Pico is a stupidly simple, blazing fast, flat file CMS.
http://picocms.org/
MIT License
3.81k stars 616 forks source link

Nice Date filter #691

Closed digitalinferno closed 4 months ago

digitalinferno commented 4 months ago

Just another adventure in the Pico Plugin system.

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

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.

PhrozenByte commented 4 months ago

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

digitalinferno commented 4 months ago

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

github-actions[bot] commented 4 months ago

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: