Show age in years in php

8

I would like to get through the information date, the person's age in years:

For example:

06/09/1991 - > 24 years 05/12/1998 - > 16 years old

Suppose I have these dates in php

$data1 = new DateTime('19910906');
$data2 = new DAteTime('19981205');

How could I do to display both in years?

    
asked by anonymous 18.11.2015 / 03:06

3 answers

12

To compare these dates with the current date use new DateTime() (to get the current date) with the diff function:

$data1 = new DateTime('19910906');
$data2 = new DateTime('19981205');

$idadeData1 = $data1->diff(new DateTime());
$idadeData2 = $data2->diff(new DateTime());

echo "Idade1: " . $idadeData1->y . " anos.";
// OUTPUT: Idade1: 24 anos.
echo "Idade2: " . $idadeData2->y . " anos.";
// OUTPUT: Idade2: 16 anos.

See the Ideone .

If it were the case of comparing the dates between them, you could do this:

$data1 = new DateTime('19910906');
$data2 = new DAteTime('19981205');

$idade = $data1->diff($data2);

The function diff will always return an object DateInterval :

object(DateInterval)[3]
  public 'y' => int 7
  public 'm' => int 2
  public 'd' => int 29
  public 'h' => int 0
  public 'i' => int 0
  public 's' => int 0
  public 'weekday' => int 0
  public 'weekday_behavior' => int 0
  public 'first_last_day_of' => int 0
  public 'invert' => int 0
  public 'days' => int 2647
  public 'special_type' => int 0
  public 'special_amount' => int 0
  public 'have_weekday_relative' => int 0
  public 'have_special_relative' => int 0

So to know the age, just access the index y , with the -> operator:

echo "A idade é de " . $idade->y . "anos."; 
// output: A idade é de 7 anos.

See the Ideone .

    
18.11.2015 / 03:22
3
  

PHP > = 5.3

Example using date_create(), date_diff() :

# Orientado a objetos
$from = new DateTime('19910906');
$to   = new DateTime('today');
echo 'Idade1 ' . $from->diff($to)->y . " anos.";

# Procedural
echo 'Idade2 ' . date_diff(date_create('19981205'), date_create('today'))->y . " anos.";

See working at Ideone.

  

Previous versions:

function minhaIdade($date) {
    return intval(substr(date('Ymd') - date('Ymd', strtotime($date)), 0, -4));
}

echo 'Idade1 ' . minhaIdade('19910906') . ' anos';
echo 'Idade1 ' . minhaIdade('19981205') . ' anos';
    
18.11.2015 / 11:34
1

One way to check age is to subtract the current date by the other date, assuming the date is in the correct format (mostly in YYYY-MM-DD , but you can also use other formats such as YYYYMMDD , DD-MM-YYYY MM/DD/YYYY ...):

echo floor((time() - strtotime('2000-10-01')) / (60 * 60 * 24 * 365));
// Resultado: 17

The time will inform the date in Unixtime format (ie second since 1970). strtotime will convert the string to Unixtime. floor will round down.

  

As is the documentation: "The use of this function for mathematical operations is not recommended.", consider the answer to @ gustavox is still more appropriate.

    
09.09.2017 / 16:16