Validate if age is over 18 years old

前端 未结 6 2336
情歌与酒
情歌与酒 2020-12-14 12:23

Just wondering, can I do this to validate that a user has entered a date over 18?

//Validate for users over 18 only
function time($then, $min)
{
    $then =          


        
6条回答
  •  攒了一身酷
    2020-12-14 13:11

    I think it is best using the DateTime class for this.

    $bday = new DateTime("22-10-1993");  
    $bday->add(new DateInterval("P18Y")); //adds time interval of 18 years to bday  
    //compare the added years to the current date  
    if($bday < new DateTime()){   
        echo "over 18";  
    }else{  
        echo "below 18";
    }
    

    DateTime::diff can also be used to compare the date with the current date.

    $today = new DateTime(date("Y-m-d"));
    $bday = new DateTime("22-10-1993");
    $interval = $today->diff($bday);
    if(intval($interval->y) > 18){
        echo "older than 18";
    }else{
        echo "younger than 18";
    }
    

    N/B: 1) for the second method , if $bday is greater than $today by 18 years or more, it will return older , so make sure date entered is less than $today . 2) DateTime works on php 5.2.0 and above

提交回复
热议问题