1

I'm trying to show an age from this code:

$dob =  $entrantInfo['dobYear'].'-'.$entrantInfo['dobMonth'].'-'.$entrantInfo['dobDay'];
$age = date_diff(date_create($dob), date_create('today'))->y;

echo $age;

but it's not working, tried different kind of tutorials but I'm still having trouble, what should I do? Cheers

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98

1 Answers1

1

Basic Example

$date1 = new DateTime('2011-03-12');
$date2 = new DateTime('2008-03-09');

$diff = $date2->diff($date1);

echo $diff->y;

Your Example

$entrantInfo['dobYear'] = '2011';
$entrantInfo['dobMonth'] = '03';
$entrantInfo['dobDay'] = '12';

$dob =  $entrantInfo['dobYear'].'-'.$entrantInfo['dobMonth'].'-'.$entrantInfo['dobDay']; // Get dynamic date    

$date1 = new DateTime($dob);
$date2 = new DateTime(); // Get current date

$diff = $date2->diff($date1);

echo $diff->y;

Would you please try above code?

Purvik Dhorajiya
  • 4,662
  • 3
  • 34
  • 43
  • thank you, this one is working when I try my own set of codes and made dob instead of separate database, by the way, how would I use my dobDay, dobMonth, dobYear for the date1? Thank you, I think I need to study more about the ->y thing @purvik7373 – d3bug_asking_answering Feb 16 '17 at 07:15
  • @Jaze I think `$dob = $entrantInfo['dobYear'].'-'.$entrantInfo['dobMonth'].'-'.$entrantInfo['dobDay'];` this one is correct. Please try this. – Purvik Dhorajiya Feb 16 '17 at 07:29
  • how should I make the $date2 as current time? – d3bug_asking_answering Feb 16 '17 at 08:08
  • You can cut out several lines from the answer -- the bit with using `date()` to get `$curr_date` is redundant as the `DateTime()` class is perfectly capable to getting the current date for itself. – Simba Feb 16 '17 at 09:50