当前日期与表单中插入的生日日期之间的差值


Difference between the current date and the birthday date inserted in a form

在表单上用户必须输入出生日期。PHP应该控制他是否已经年满18岁。

$birth = $_POST['data_nascita']; 
$str_birth = strtotime ($birth );        
$today = date("m/d/Y");
$str_today = strtotime ($today);                
if($today - $str_today < 567648000) {
    echo'you can't drive a car in Italy because you are underage';exit(); 
}
// 18 years * 31536000 second in 1 year = 567648000

如果我把1998年9月14日的日期放在出生字段(今天是2016年9月13日,所以18年还没有完全度过),控制不起作用;由一九九八年九月十五日起生效。

为什么我失去了2天?

我建议使用DateTime类,因为它具有所有日期和时间功能以及内置的数学。

一个例子:

$birth = new DateTime($_POST['date_of_birth']);
$today = new DateTime('now');
$diff = $birth->diff($today);
if($diff->format('%Y') > 18) {
    echo "Can drive";
} else {
    echo "Can't Drive";
}