Gianluis Gianluis - 1 year ago 71
PHP Question

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

On a form, the user must enter the date of birth. PHP should control if he has already accomplished 18 years.

$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

If I put on birth field the date of 14 September 1998 (today is 13 September 2016, so 18 years don't entirely spend yet), the control doesn't work; it works starting from 15 September 1998.

Why I lost 2 days?

Answer Source

I would recommend using the DateTime Class as it has all Date and Time functionality and maths built into it.

An Example:

$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";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download