To compare these dates with the current date use new DateTime()
(to get the current date) with the function diff
:
$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 on Ideone.
If it were the case to compare the dates between them, you could do so:
$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 on Ideone.
That’s what I was trying to do.
– DiChrist