1

I have a in which my DOB is registered depending on the selection in a drop down list.

 Date of Birth:
    <select name="DOBDay" required>
    <option> Day </option>
    <option value="1">1</option>
    <option value="2">2</option>
    // etc ....

The same approach is adopted for month and year. As a result of this, when I process the registration form, data is obtained from these three dropdowns and are assigned to three different variables:

$DOBDay       = strip_tags(@$_POST['DOBDay']);
$DOBMonth     = strip_tags(@$_POST['DOBMonth']);
$DOBYear      = strip_tags(@$_POST['DOBYear']);

I need a way I can get the current age of the user based on the DOB provided, but since I have it stored in three different variables (and three different columns in my database), I don't know how I can get their current age. Any ideas?

More details:

I need an $age variable which will calculate the age and I need it to be of type int, so that I can store the age in the age column in my db.

Freddy
  • 683
  • 4
  • 35
  • 114
  • Possible duplicate of [PHP calculate age](http://stackoverflow.com/questions/3776682/php-calculate-age) – C.Liddell Mar 10 '16 at 14:12

2 Answers2

1

How about this:

$birthday = new DateTime();
$birthday->setDate($DOBYear, $DOBMonth, $DOBDay);
$now = new DateTime("now");
$age = $birthday->diff($now);
echo $age->y . " years old";
bytesized
  • 1,502
  • 13
  • 22
  • `$DOBMonth` is a string, rather than a numerical value i.e. "January" as appose to "01" . Nevertheless, I have written several if statements i.e. `if ($DOBMonth == "January"){ $DOBMonth2 = "01";}`, and have tried to add `$age` variable inside my INSERT query, and get a fatal error - `Object of class DateInterval could not be converted to string ` which is the line where `$age` is in the INSERT query? P.s. age is of type int in my table. – Freddy Mar 09 '16 at 23:44
  • @Freddy You are correct: `$age` is of type `DateInterval`. If you want the number of years in the interval, use `$age->y` as I did in my answer. – bytesized Mar 09 '16 at 23:47
  • @Freddy Also, I believe you could also use `date_parse($DOBMonth)['month']` to convert from a date string to a date number. – bytesized Mar 09 '16 at 23:52
0

Take your strings and concatenate them into a date format and use code similar to this.

<?php
  //date in mm/dd/yyyy format; or it can be in other formats as well
  $birthDate = "$DoBMonth/$DoBDay/$DoBYear";
  //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]));
  echo "Age is:" . $age;
?>
McCormick32
  • 185
  • 11