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 .