用PHP计算年龄

时间:2018-07-11 07:29:53

标签: php codeigniter

伙计们,我正在做我的同事项目,他使用下面的代码从数据库存储年龄并在视图中显示年龄

他从选择标签中选择日期和月份。

查看BOD select tag image

.as-console-wrapper { max-height: 100% !important; top: 0; }

result image

控制器

<?php $today = date("Y");
  $year = $today - 18;?>

     <select class="form-control" id="date" name="day" >
        <option label=01 value=01>01</option>
        <option label=02 value=02>02</option>
        <option>.......</option>            
        <option label=30 value=30>30</option>
        <option label=31 value=31>31</option>
     </select>
     <select class="form-control" id="month" name="month" >
        January
        <option label=January value=01>January</option>
        February
        <option label=February value=02>February</option>
        <option>.......</option>
        November
        <option label=November value=11>November</option>
        December
        <option label=December value=12>December</option>
     </select>  

<select class="form-control" id="year" name="year" >
   <?php for($i = 0; $i <= 75; $i++):?>
     <option value=<?=$year?>><?=$year?></option>
     <?php echo $year = $year -1 ;?>
   <?php endfor;?>
</select>

当我选择其他任何日期时,它都可以完美运行。

但是当我选择(01/01/2000)日期时,它在数据库中将年龄存储为-1

3 个答案:

答案 0 :(得分:1)

通过串联字符串生成生日。

$date1 = date_create("2013-03-15");  // generate this by "$date-$month-$year"; // your case
$date2 = date("Y-m-d"); // get today's date
$diff = date_diff($date1,$date2);  //here you get the difference

您可以应用数学运算来获得确切的确切年份和月份。

答案 1 :(得分:0)

**Php Version >= 5.3**
# **get date and change date formate**
$from = new DateTime('1970-02-01');
$to   = new DateTime('today');
echo $from->diff($to)->y;
echo date_diff(date_create('1970-02-01'), date_create('today'))->y;

**Mysql Version >= 5.0**

SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age

答案 2 :(得分:0)

我在该问题中看不到任何试图根据问题标题建议计算用户年龄的代码-因此无法提出如何适当地编辑代码的建议。但是,正如我在评论中提到的那样,@ Danyal和@Anil在其他答案中使用了它,将DateTime类及其关联方法一起使用将更加容易和可靠。

下面的代码只是对该问题的快速重写,以使其可行并使演示正常工作。处理用户选择的代码在下面的if代码块内,应加注释。

$today = date( 'Y' );
$year = $today - 18;
$maxyears = 120;


$html=array();

$html[]='<form method="post">';

/* days */
$html[]='<select class="form-control" name="day">';
for( $i=1; $i <= 31; $i++ )$html[]=sprintf('<option value=%d>%d',$i,$i);
$html[]='</select>';

/* months */
$html[]='<select class="form-control" name="month">';
for( $i=1; $i <= 12; $i++ )$html[]=sprintf('<option value=%d>%s', $i, date('F',mktime( 0, 0, 0, $i ) ) );
$html[]='</select>';

/* years */
$html[]='<select class="form-control" name="year">';
for( $i=$year; $i >= ( $today - $maxyears); $i-- )$html[]=sprintf('<option value=%d>%d',$i,$i);
$html[]='</select>';


$html[]='<input type="submit" />';
$html[]='</form>';



/* output menus */
echo implode( PHP_EOL, $html );


/*****  Process Form submission and calculate Age *****/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['day'], $_POST['month'], $_POST['year'] ) ){

    /* Establish rules for filtering POSTED data */
    $args=array(
        'day'   =>  FILTER_SANITIZE_NUMBER_INT,
        'month' =>  FILTER_SANITIZE_NUMBER_INT,
        'year'  =>  FILTER_SANITIZE_NUMBER_INT
    );
    /* Filter POST data */
    $_POST=filter_input_array( INPUT_POST, $args );

    /* Extract data to variables */
    extract( $_POST );

    /* create a new date using supplied POST data - using `mktime` to generate a valid timestamp */
    $date = date( 'Y-m-d', mktime( 0, 0, 0, $month, $day, $year ) );

    /* create DateTime objects and calculate age ( date difference ) */
    $now = new DateTime();
    $dob = new DateTime( $date );

    /* use the `diff` method to find the difference between two dates */
    $diff = $now->diff( $dob );

    /*
        show the age 
        use the `$diff->format('%y')` method or the shorthand method `$diff->y`
    */
    printf('Age: %d', $diff->y );   #same as $diff->format('%y');

查看getAge函数会产生非常奇怪的结果-所以我对其进行了调整并得出以下结果-似乎或多或少做了所需的工作。

function getAge( $date ) {
    $now = date( 'Y' );
    $diff = $now - $date;
    if( strtotime( '+' . $diff . ' years', strtotime( $date ) ) < time() ) $diff--;
    return $diff;
}

echo getAge( 2017 ); // -> 1
echo getAge( 2000 ); // -> 18