Verify Age With PHP DateTime

Date:

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';
}

?>

 

Amarendra
Amarendra
Stock Trader, SEO, Music Producer

Leave a reply

Please enter your comment!
Please enter your name here

Share post:

Subscribe

Popular

More like this
Related

Tango Live: Free Guide to Exclusive Features and Benefits

Introduction Welcome to our comprehensive guide on Tango Live, the...

How to Setup SailPoint and Manage IdentityIQ with Compass

Introduction to SailPoint Technology and SailPoint Compass: A Comprehensive...

XXVI Video Player – Exclusive Multimedia Companion

Introduction to XXVI Video Player Download XXVI Video Player, Link...

How to Use Telegram Web Login for Windows and Mac

Telegram Web Login: A Comprehensive How to Guide Telegram is...