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

How to calculate users age

Hello :-)

i have a mysql database table, with the fields day, month and year.

How can i calculate the users age, with this data.

Rgds

Stefan

https://forum.phalcon.io/discussion/1748/date-sub-interval-mysql

https://github.com/phalcon/incubator/blob/master/Library/Phalcon/Db/Dialect/MysqlExtended.php

// services.php
$di->set('db', function() use ($config) {
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host"         => $config->database->host,
        "username"     => $config->database->username,
        "password"     => $config->database->password,
        "dbname"       => $config->database->name,
        "dialectClass" => '\Phalcon\Db\Dialect\MysqlExtended'
    ));
});
// MysqlExtended.php
class MysqlExtended extends Mysql
{
    public function getSqlExpression(array $expression, $escapeChar = null, $bindCounts = NULL)
    {
        if ($expression["type"] == 'functionCall') {
            switch ($expression["name"]) {
                case 'AGE':
                    return "DATE_FORMAT(FROM_DAYS(DATEDIFF(CURRENT_DATE()," . $this->getSqlExpression($expression["arguments"][0]) . ")), '%Y')";
                    break;
            }
        }
    }
}
new Query("SELECT AGE(CONCAT(year,'-',month,'-',day)) FROM user");


77.7k
Accepted
answer

You may also implement it at model level:

class User extends Model
{
    public function getAge()
    {
        $from = new DateTime($this->year.'-'.$this->month.'-'.$this->day);
        $to   = new DateTime('today');
        return $from->diff($to)->y;
    }
}


60.0k

Hi Lajos,

i will try it and reply.

Thank you again :-)

Rgds

Stefan



60.0k

Hi Lajos,

sorry for my late answer :-)

I have a Model called Birthday.php (day, month, year) and i have insert your code, but how can i implement the age into my template via Volt?

Rgds

Stefan



60.0k

Hi Lajos,

don't know if you will read that, but your example with Model is almost working. Only a little change is to do, we have to insert a backslash before the DateTime class, because phalconphp doesn't know it:

public function getAge(){
    $from = new \DateTime($this->year.'-'.$this->month.'-'.$this->day);
    $to   = new \DateTime();
    return $from->diff($to)->y;
}

And to call the function in my template via volt, we have to do that:

 {% for birthday in user.birthday %}    
   {{  birthday.getAge() }} 
 {% endfor %}

Thx for your help

Rgds

Stefan