CakePHP: a temporary helper to show age

I have a MySQL DATETIME field that contains the user's date of birth. I want to use this date to display the user's age in years.

Is there a way for the Core Assistant to do this?

Also, why, when you add a DATETIME field to a form in Cake, doesn't it make it possible to select a date less than 1990?

Thank,

Jonesi

+3
source share
5 answers

Adding a new answer because the code will be shown better. How will I do it:

create a virtual field in your model .

var $virtualFields = array(
   'age' => "YEAR(NOW())-YEAR(YourModelName.datetimeField)"
);

Then use it as a normal field in the model. :)

+3
source

timeAgoInWords

<?php echo $this->Time->timeAgoInWords(
      '1975-12-29 13:40', 
      array(
            'end'=>'+150 years'
      )
);?>

150 ( , 150- :)))).

: : 34 , 9 , 4

API CookBook,

+4

timeAgoinWords() , . Book

. . Book.

+3

PHP - . , , , .

, , . 365 - .

You can customize the date pick range in the Cake form helper.

+1
source

I always use this proven method:

/*
 * @return int age (0 if both timestamps are equal or empty, -1 on invalid dates)
 * 2009-03-12 ms
 */
function age($start = null, $end = null, $accuracy = 0) {
    $age = 0;
    if (empty($start) && empty($end) || $start == $end) {
        return 0;
    }

    if (empty($start)) {
        list($yearS, $monthS, $dayS) = explode('-', date(FORMAT_DB_DATE));
    } else {
        $startDate = $this->fromString($start);
        $yearS = date('Y', $startDate);
        $monthS = date('m', $startDate);
        $dayS = date('d', $startDate);
        if (!checkdate($monthS, $dayS, $yearS)) {
            return -1;
        }
    }
    if (empty($end)) {
        list($yearE, $monthE, $dayE) = explode('-', date(FORMAT_DB_DATE));
    } else {
        $endDate = $this->fromString($end);
        $yearE = date('Y', $endDate);
        $monthE = date('m', $endDate);
        $dayE = date('d', $endDate);
        if (!checkdate($monthE, $dayE, $yearE)) {
            return -1;
        }
    }

    $n_tag = $dayE;
    $n_monat = $monthE;
    $n_jahr = $yearE;
    $g_tag = $dayS;
    $g_monat = $monthS;
    $g_jahr = $yearS;
    $g_date = mktime(0,0,0,$g_tag,$g_monat,$g_jahr);

    if (($n_monat>$g_monat)||(($n_monat == $g_monat)&&($n_tag>$g_tag))||(($n_monat == $g_monat)&&($n_tag==$g_tag))) {
        $age = $n_jahr-$g_jahr; // is correct if one already had his birthday this year
    } else {
        $age = $n_jahr-$g_jahr-1; // is correct if one didnt have his birthday yet in this year
    }
    return $age;
}

it can be reinstalled but it works with leap years and all sorts of things. so I never worried ...

it uses a constant that you don't have

its simple: define ('FORMAT_DB_DATE', 'Ym-d');

0
source

Source: https://habr.com/ru/post/1771569/


All Articles