我正在寻找一种方法来计算用户以html格式输入出生日期的年龄,然后按提交按钮。我看到了类似的问题,但他们都是关于计算已经存在的年龄,但在这里我说的是输入日期然后计算年龄。
我尝试制作代码,但它给了我错误的年龄:
<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;
}}
?>
答案 0 :(得分:1)
您的日期是一个字符串,您尝试使用它来计算,首先尝试解析字符串到日期:
$birthDate = $year.'-'.$month.'-'.$day;
$time = strtotime($birthDate);
$birthDate= date('Y-m-d',$time);
也关闭</form>
答案 1 :(得分:0)
简单的PHP代码来计算出生日期的年龄
$Age = ((time()- strtotime ($dateofbirth)) /(3600 * 24 * 365))