如果年龄超过18岁,请确认

New*_*ewb 8 php

只是想知道,我可以这样做来验证用户输入的日期超过18岁吗?

//Validate for users over 18 only
function time($then, $min)
{
    $then = strtotime('March 23, 1988');
    //The age to be over, over +18
    $min = strtotime('+18 years', $then);
    echo $min;
    if (time() < $min) {
        die('Not 18');
    }
}
Run Code Online (Sandbox Code Playgroud)

偶然发现这个函数date_diff:http://www.php.net/manual/en/function.date-diff.php 看起来,更有希望.

mau*_*ris 23

为什么不?对我来说唯一的问题是用户界面 - 如何优雅地向用户发送错误消息.

另一方面,你的功能可能无法正常工作,因为你没有过正常的生日(你使用固定的生日).你应该将'1988年3月23日'更改为$ then

//Validate for users over 18 only
function validateAge($then, $min)
{
    // $then will first be a string-date
    $then = strtotime($then);
    //The age to be over, over +18
    $min = strtotime('+18 years', $then);
    echo $min;
    if(time() < $min)  {
        die('Not 18'); 
    }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以:

// validate birthday
function validateAge($birthday, $age = 18)
{
    // $birthday can be UNIX_TIMESTAMP or just a string-date.
    if(is_string($birthday)) {
        $birthday = strtotime($birthday);
    }

    // check
    // 31536000 is the number of seconds in a 365 days year.
    if(time() - $birthday < $age * 31536000)  {
        return false;
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

  • 另外,请记住一年在技术上一年365.242199天.所以你应该乘以31556926而不是31536000.此外,谷歌对这些类型的计算非常好,只要问谷歌"1秒钟":) (8认同)

zee*_*han 14

以下是我在多伦多银行系统中使用的简化摘录,考虑到366天的闰年,这总是很完美.

/* $dob is date of birth in format 1980-02-21 or 21 Feb 1980
 * time() is current server unixtime
 * We convert $dob into unixtime, add 18 years, and check it against server's
 * current time to validate age of under 18
 */

if (time() < strtotime('+18 years', strtotime($dob))) {
   echo 'Client is under 18 years of age.';
   exit;
}
Run Code Online (Sandbox Code Playgroud)


non*_*hto 6

我认为最好为此使用 DateTime 类。

$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";
}
Run Code Online (Sandbox Code Playgroud)

DateTime::diff 也可用于将日期与当前日期进行比较。

$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";
}
Run Code Online (Sandbox Code Playgroud)

N/B: 1) 对于第二种方法,如果 $bday 比 $today 大 18 年或更长时间,它将返回旧的,因此请确保输入的日期小于 $today 。2) DateTime 适用于 php 5.2.0 及以上