Reputation: 867
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.
Upvotes: 1
Views: 489
Reputation: 1522
How about this:
$birthday = new DateTime();
$birthday->setDate($DOBYear, $DOBMonth, $DOBDay);
$now = new DateTime("now");
$age = $birthday->diff($now);
echo $age->y . " years old";
Upvotes: 1
Reputation: 185
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;
?>
Upvotes: 0