在PHP中转换和读取日期

在PHP中转换和读取日期,php,yii2,Php,Yii2,我正在使用oracle数据库表,它有一个数据类型为DATE的BIRTH_DATE列。此列中的数据以dd-mm-yy格式输入,例如75年5月14日。这一年将被解读为1975年。 我想用那一栏来计算年龄。然而,在我的代码中,年份被解读为2075年。 我该如何解决这个问题 $today_date = date_create(date('Y/m/d')); $birth_date = date_create($BIRTH_DATE); $years = date_diff($bi

我正在使用oracle数据库表,它有一个数据类型为DATE的BIRTH_DATE列。此列中的数据以dd-mm-yy格式输入,例如75年5月14日。这一年将被解读为1975年。 我想用那一栏来计算年龄。然而,在我的代码中,年份被解读为2075年。 我该如何解决这个问题

    $today_date = date_create(date('Y/m/d'));
    $birth_date = date_create($BIRTH_DATE);
    $years = date_diff($birth_date, $today_date)->format('%y');
您可以尝试:

<?php
$timestamp = strtotime("14-MAY-75");
$birthYear = date("Y", $timestamp);
$currentYear =  date("Y");

$age = $currentYear - $birthYear;

echo "Age = ". $age;

我找到了解决方法

$retiring_staff = [];

    $staff = StafflistView::find()
            ->SELECT(['PAYROLL_NO','EMP_ID','BIRTH_DATE','RETIRE_AGE'])
            ->all();

    $today_date = date_create(date('Y/m/d'));

    foreach($staff as $st){           
        $birth_timestamp = strtotime($st->BIRTH_DATE);
        $birth_date = date("Y/m/d", $birth_timestamp);
        $birth_year = substr($birth_date, 0, 4);

        $today_date = date('Y/m/d');
        $today_year = substr($today_date, 0, 4);
        /**
         * The BIRTH_DATE in the db is formatted in dd-mm-yy Eg 14-MAY-75.
         * Therefore the year is prefixed with 20 by the date function above.
         * The year is to be read as 14-MAY-1975 instead of 14-MAY-2075. 
         * YOB is never in the future, so we must account for the added 100 years.
         * We need not worry about staff born 100 years ago, beacuse retirement age is below this.
         */
        if((int)$birth_year > (int)$today_year){
            (int)$birth_year = (int)$birth_year - (int)100;
            $birth_year = strval($birth_year);
            $birth_date = str_replace(substr($birth_date, 0, 4), $birth_year, $birth_date);
        }

        $birth_date = date_create($birth_date);
        $today_date = date_create($today_date);
        $age = date_diff($birth_date, $today_date);

        if((int)$age->y > $st->RETIRE_AGE)
        {
            $arr = [
                'emp_id' => $st->EMP_ID,
                'birth_date' => $st->BIRTH_DATE,
                'retire_age' => $st->RETIRE_AGE,
                'age' => strval($age->y).' years '.$age->m.' months',
            ];
            $retiring_staff[] = $arr;
            unset($arr);
        }
    }
    return $retiring_staff;

您能否澄清使用的是哪种格式,它是
dd-mm-yy
或类似于
1975年5月14日
,但不能两者都是。我们可以期待
01-01-11
01-Janur-11
1-Janur-11
01-JAN-11
,等等。例如,列中的日期输入为75年5月14日
$today\u date=date\u create(日期('Y/m/d')可以缩短为
$today\u date=date\u create()。将日期作为文本处理不仅是不必要的,而且常常会导致错误的结果。而且,
DATE
列没有任何格式。当您转换值以显示时会发生格式化。遗憾的是,这也不起作用。我也有同样的问题。你能把你从数据库里得到的信息变为变量吗。