bikey77
bikey77

Reputation: 6672

PHP compare dates in registration form

I have a registration form in which I need to verify that the 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.

Upvotes: 0

Views: 567

Answers (2)

Nick
Nick

Reputation: 6965

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.

Upvotes: 3

Vijay
Vijay

Reputation: 5433

$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...

Upvotes: 0

Related Questions