-3

How can I calculate an age in years and months, given a birth date of format YYYY-MM-DD? Is it possible using the Date() function?

I have done in php. Below is my code

   $dateOfBirth = date("Y-m-d", strtotime($post->date_of_birth));
   $today = date("Y-m-d");
   $age= $diff->format("%Y Years, %M Months");
   echo $age;

I am getting the results in json.Can i embed the php code in json while diplaying or how can i get the age in years and months using date of birth....??

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
user5370838
  • 111
  • 2
  • 14
  • You can give (javascript) Date() and iso formatted date and it will create an object representation of that date. Then you just have to do math against the current date. Keep in mind that unless you add additional logic, the age will be based entirely upon the date settings on the clients machine. If it is very important that the age be accurate, then you'll have to account for that, or either calcuate the age on the server side. – Taplar Nov 29 '18 at 17:43
  • Is this database related by any chance? – Funk Forty Niner Nov 29 '18 at 17:50
  • why is this tagged as javascript and jquery? – Funk Forty Niner Nov 29 '18 at 17:51
  • From PHP manual user contributions 1 (http://php.net/manual/en/function.date-diff.php) https://3v4l.org/ZfCBJ – user3783243 Nov 29 '18 at 17:51

1 Answers1

1

In php you can do this using the datetime object:

$dateOfBirth = new DateTime($post->date_of_birth);
$today = new DateTime();
$diff = $today->diff($dateOfBirth);
//echo $diff->format("%Y Years, %M Months");

Then if you want to output that as json you can just:

echo json_encode(['diffString' => $diff->format("%Y Years, %M Months")]);
Bryan
  • 3,449
  • 1
  • 19
  • 23
  • But i am using ajax and retrieving the data in json format and now i need to calculate the age from date of birth – user5370838 Nov 29 '18 at 17:55
  • Just send the diff in the response so you don't have to do the same work twice. – Bryan Nov 29 '18 at 17:56
  • You can use array_merge php function. `array_merge(['diffString' => $diff->format("%Y Years, %M Months")], $myOtherArray)` – Bryan Nov 30 '18 at 16:44