0

I'm trying to calculate age. I'm using this code and it works great for the sample birthdate, but I can't figure out how to get $birthDate to equal my three separate variables $day, $month, $year that are stored in my database for each user. How would I do this so $birthDate = $day/$month/$year and works with the age calculator below?

<?php
$birthDate = "12/17/1983";
$birthDate = explode("/", $birthDate);
$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])-1):(date("Y")-$birthDate[2]));
echo "Age is:".$age;
?>
user2250471
  • 1,002
  • 3
  • 10
  • 23

1 Answers1

3

this is tried and tested in my registration system

 //date in mm/dd/yyyy format; or it can be in other formats as well
  $birthDate = $_POST['month']."/".$_POST['date']."/".$_POST['year'];
  //explode the date to get month, day and year
  $birthDate = explode("/", $birthDate);
  //get age from date or birthdate
  $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], 
  $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])-1):(date("Y")-$birthDate[2]));

use date time picker or validate the values being submitted via javascript to allow only valid dates

  • 3
    I hope you're validating those $_POST parameters in your "registration" system. – Ryan Oct 17 '13 at 17:01
  • 1
    @RPM what do you mean validating? im using a date time picker for the user to enter his birthday not texfield or combobox if thats what you mean – Jose Samaniego Oct 17 '13 at 17:12
  • @JoseSamaniego ask [curl](http://curl.haxx.se/) if it understands how a date picker work. Or maybe [this](http://sqlmap.org/) will try to use your date picker ;-) – Fabio Oct 17 '13 at 21:34