Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.phalconphp.com/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");


38.2k
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;
    }
}


19.4k

Hi Lajos,

i will try it and reply.

Thank you again :-)

Rgds

Stefan



19.4k

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



19.4k

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