简体   繁体   中英

Calculate age in php

Hey guys I am working on my colleague project and he used below code to store age from database and shows age in view

He select date and month from select tag.

view BOD select tag 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>

result image

controller

 public function user_register()
{
    $data = array(          
        'u_day'=>$this->input->post('day'),
        'month'=>$this->input->post('month'),
        'year'=>$this->input->post('year'),
        'age'=>$this->getAge($this->input->post('year')),            
    );
    $id = $this->admin_model->insertData('users',$data);
    $sess = array(
        'userid'=>$id,
        'fname'=>$this->input->post('first_name'),
        'mname'=>$this->input->post('middle_name'),
        'lname'=>$this->input->post('last_name'),
        'gender'=>$this->input->post('gender'),
        'reg'=>'1',
    );
    $this->session->set_userdata($sess);

    redirect($this->config->item('base_url').'profile/basic_details');
}

public function getAge($then) {
    $then_ts = strtotime($then);
    $then_year = date('Y', $then_ts);
    $age = date('Y') - $then_year;
    if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
    //print_r($age);exit;
    return $age;
}

It works perfectly when I select any other date.

but when I select (01/01/2000) date it store age in database as -1

Generate the birth date by concatenating the strings.

$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

You can apply mathematical operations to get exact exact years and months.

**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

I can not see any code in the question that attempts to calculate the age of a user as suggested by the title of the question - consequently can not suggest how to edit the code appropriately. However, as I mentioned in my comment and has been used elsewhere in answers by @Danyal & @Anil, it would be easier and more reliable to use the DateTime class with it's associated methods.

The code below is just a quick rewrite of the question to make it viable and enable the demo to work. The code that processes the user selection is within the if code block below and should be well commented.

$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');

Looking at the getAge function produced very odd results - so I tweaked it and arrived at the following - seems to more or less do what is needed.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM