首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP中的转换和读取日期

PHP中的转换和读取日期
EN

Stack Overflow用户
提问于 2020-05-16 10:01:22
回答 2查看 56关注 0票数 1

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

代码语言:javascript
复制
    $today_date = date_create(date('Y/m/d'));
    $birth_date = date_create($BIRTH_DATE);
    $years = date_diff($birth_date, $today_date)->format('%y');
EN

回答 2

Stack Overflow用户

发布于 2020-05-16 10:06:23

你可以试试:

代码语言:javascript
复制
<?php
$timestamp = strtotime("14-MAY-75");
$birthYear = date("Y", $timestamp);
$currentYear =  date("Y");

$age = $currentYear - $birthYear;

echo "Age = ". $age;
票数 0
EN

Stack Overflow用户

发布于 2020-05-16 12:52:09

我找到了解决办法。

代码语言:javascript
复制
$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;
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61835017

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档