如何确认并通过出生日期显示其年龄?
if ($_POST['DateOfBirth_Month'] == 'January') {
$DateOfBirth_Month = $_POST['DateOfBirth_Month'];// January
}
else if ($_POST['DateOfBirth_Month'] == 'February') {
$DateOfBirth_Month = $_POST['DateOfBirth_Month'];// February
}
if ($_POST['DateOfBirth_Day'] == '1') {
$DateOfBirth_Day = $_POST['DateOfBirth_Day'];// 1
}
else if ($_POST['DateOfBirth_Day'] == '2') {
$DateOfBirth_Day = $_POST['DateOfBirth_Day'];// 2
}
if(is_numeric($_POST['DateOfBirth_Year']) && $_POST['DateOfBirth_Year'] > 1969)
{
$DateOfBirth_Year = $_POST['DateOfBirth_Year'];
}
else if (is_numeric($_POST['DateOfBirth_Year']) && $_POST['DateOfBirth_Year'] < 1970)
{
echo'<p><font color ="red">Please enter 1970 and above!</font></p>';
}
else
{
echo '<p><font color="red">Enter NUMBER for the year of date of birth!</font></p>';
}
答案 0 :(得分:0)
答案 1 :(得分:0)
我们假设我发布了我的生日:
$_POST["DateOfBirth_Year"] = 1980;
$_POST["DateOfBirth_Month"] = "October";
$_POST["DateOfBirth_Day"] = 20;
我使用此功能处理POST
function POST($var) {
if(!isset($_POST[$var])) return null;
return $_POST[$var];
}
首先我们阅读输入
$dob_m = POST('DateOfBirth_Month');
$dob_y = intval(POST('DateOfBirth_Year'));
// lets allow say 24th to be 24
$dob_d = intval(POST('DateOfBirth_Day'));
为了便于检查和获取月份索引,让我们创建月份数组
$months = array("January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December");
现在检查月份
$month_ok = array_search($dob_m,$months)!==false;
if(!$month_ok) return; // some reasonable error handling should be here
...并获得月份指数
$dob_m = array_search($dob_m,$months) + 1;
然后我们应该使用date函数验证日期(30.2.1980无效)
$stamp = mktime(0,0,0,$dob_m,$dob_d,$dob_y);
$dob_ok = date("Y",$stamp)==$dob_y &&
date("n",$stamp)==$dob_m && date("j",$stamp)==$dob_d;
if(!$dob_ok) return; // proper error handling here, too
最后,让我们使用DateTime对象
计算年龄$dob_dt = new DateTime(date("Y-m-d H:i:s",$stamp));
$now_dt = new DateTime("now");
$age = $dob_dt->diff($now_dt)->format("%y");
if($age<0 || $age>125) return; // error handling here
echo $age; // should be my age