Verify Age With PHP DateTime

There are times when a site needs to check the age of a person, usually for legal reasons. This small script shows how to check a person is of a given age, including leap years. Buy using the PHP DateTime class, php is able to account for dates at a system level.

<?php

/**
*
* Check minimum age. Defaults to 18 years
*
* @param    string    $dob    The date of birth
* @param    int    
* @return    bool
*
*/
function validate_age( $dob, $min_age=18 )
{
        $dob     = new DateTime( $dob );
        $min_age = new DateTime( 'now - ' . $min_age . 'years' );
        return $dob <= $min_age;
}

?>

USAGE

<?php

/**
*
* Check minimum age. Defaults to 18 years
*
* @param        string  $dob    The date of birth
* @param        int     
* @return       bool
*
*/
function validate_age( $dob, $min_age=18 )
{
        $dob     = new DateTime( $dob );
        $min_age = new DateTime( 'now - ' . $min_age . 'years' );
        return $dob <= $min_age;
}

// the person must be at least 21 years of age
$age = 21;

// persons date of birth (dd-mm-yyyy)
$dob = '20-4-1981';

if( validate_age( $dob, $age ) === false )
{
    echo 'Person is not 21 years old';
}
else
{
    echo 'Person is 21 or over';
}

?>

 

Subscribe

Related articles

There is brand-new Xiaomi Wireless AR Smart Glasses

Xiaomi, the Chinese multinational electronics company, has recently launched...

The OnePlus 11R has been revealed to use a Snapdragon 8+ Gen 1 processor

OnePlus is having a big event on February 7, where...

Zoom Lays Off 1,300 Employees: A Look at the Impact and Reactions

Zoom, the popular video conferencing platform, has recently announced...

The Future of Bitcoin and Cryptocurrency Outlook in 2023

Bitcoin and cryptocurrency have come a long way since...
Amarendra Singh
Amarendra Singh
Stock Trader, SEO, Music Producer

Leave a reply

Please enter your comment!
Please enter your name here