We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

diffForHumans in Phalcon?

Hello!

In laravel I could use diffForHumans to get dates in human form, like 5 days ago instead of the date.


$user->created_at->diffForHumans();

returns, say, 20 days ago.

How do I do this in Phalcon? My mysql contains datetime.

Currently I'm using (in volt):


Registered: {{ user.created_at }}<br>

Thank you!



4.0k
edited Jul '15

Laravel used Carbon (I think).

You can install Carbon. For example via composer

$ composer require nesbot/carbon

and create filter

$di->set('volt', function ($view, $di) {

    $volt = new VoltEngine($view, $di);

    $volt->setOptions(array(
        "compiledPath" => APP_PATH . "cache/volt/",
    ));

    $compiler = $volt->getCompiler();

    $compiler->addFilter('diffForHumans', function($resolvedArgs, $exprArgs){
        return '\Carbon\Carbon::createFromFormat("Y-m-d H:i:s", '.$resolvedArgs.')->diffForHumans()';
    });

    return $volt;
}, true);

$di->set('view', function () use ($config) {

    $view = new View();

    $view->setViewsDir(APP_PATH . $config->application->viewsDir);

    $view->registerEngines(array(
        ".volt" => 'volt'
    ));

    return $view;
});

In Volt template

Registered: {{ user.created_at|diffForHumans }}<br>

Hey Paulius, thanks for the reply! I remembered carbon after I found my own sollution, maybe I'll switch. Think one is better than the other?

This is what I'm currently using:


    public function humanTiming()
    {
        $time = strtotime($this->created_at);
        $time = time() - $time; // to get the time since that moment

        if($time < 5){
            return 'Just now';
        }

        $tokens = array (
            31536000 => 'year',
            2592000 => 'month',
            604800 => 'week',
            86400 => 'day',
            3600 => 'hour',
            60 => 'minute',
            1 => 'second'
        );

        foreach ($tokens as $unit => $text) {
            if ($time < $unit) continue;
            $numberOfUnits = floor($time / $unit);
            return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s ago':' ago');
        }
    }

Thank you! :)