-2

I am looking for a way to calculate the age when the user enter his birth date in html form and press the submit button. I saw similar questions but they all about calculating already existing age but here I am talking about entering date and then calculating the age.

I tried to make the code but it gives me wrong age:

<form action="test.php" method="post">   

Enter your date of birth:
<select name="month" >
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>

</select>
<select name="day" id="day">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="year" id="year">
<option value="1">2013</option>
<option value="2">2012</option>
<option value="3">2011</option>
</select>
<input type="submit" name="submit" value="age" >


<?php
if (isset($_POST['submit']))
{
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
if ($year != '' && $month != '' && $day != '') {
$birthDate = $year.'-'.$month.'-'.$day;

$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[2], $birthDate[1],  $birthDate[0]))) > date("md") ? ((date("Y")-$birthDate[0])-1):(date("Y")-$birthDate[0]));
echo "Age is: ".$age;
}}
?>
4

2 回答 2

2

您的日期是一个字符串,您尝试使用它进行计算,首先尝试将字符串解析为日期:

$birthDate = $year.'-'.$month.'-'.$day;

$time = strtotime($birthDate);

$birthDate= date('Y-m-d',$time);

也关闭</form>

于 2013-08-27T23:42:06.757 回答
0

从出生日期计算年龄的简单 php 代码

$Age = ((time()- strtotime ($dateofbirth))  /(3600 * 24 * 365))
于 2013-12-30T12:47:31.400 回答