PHP compare dates in registration form
I have a registration form in which I need to verify that t开发者_如何学运维he user is over 18 years old (the user fills in his date of birth by selecting the values from 3 drop down menus, day, month, year). Which is the best way to do it? I'm trying to use mktime and subtracting the date of birth from the current date but can't get it right.
I'd use DateTime, and do something along the following lines:
<?php
$year = (int) $_POST['year'];
$month = (int) $_POST['month'];
$day = (int) $_POST['day'];
$now = new DateTime();
$dob = new DateTime("$year-$month-$day");
$age = (int) $now->diff($dob)->format("%y");
if ($age < 18) {
// Denied
}
Working with dates are usually problematic due to edge cases, so I find it best to leave it to libraries designed and developed by people who have considered the edge cases.
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%y');
The above code returns the result in years, you can check with the years in a conditional loop to allow users for registration...
精彩评论