我怎样才能计算出不低于18的日期

时间:2016-05-13 08:00:51

标签: php

我试图找到不少于18年的日期,我尝试了以下代码,但它不适用于我。

// validate birthday
function validateAge($then, $min)
{
    // $then will first be a string-date
    $then = strtotime($then);

    echo "<br>";
    echo 'test1-';
    var_dump( $then );

    exit;
    //The age to be over, over +18
    $min = strtotime('+18 years', $then);

    if(time() < $min)  {
        die('Not 18'); 
    }
}

$res = validateAge('2016-02-29', $min = 18);

var_dump($res);

我看到上面的问题,你可以看到,日期无效,即使我通过错误的日期,它显示$ then = strtotime($ then);

var_dump($ then)显示int

我的问题是,如果我们传递无效日期,它如何打印时间戳,事件。

5 个答案:

答案 0 :(得分:1)

你的逻辑是正确的。去除死亡,退出和不需要的回声

function validateAge($then, $min)
{
    // $then will first be a string-date
    $then = strtotime($then);

    //The age to be more then min years
    $min = strtotime('+'. $min . ' years', $then);

    return time() > $min;
}

$res = validateAge('2016-02-29', $min = 18);
echo $res ? 'O\'key' : "Not $min years"; 

demo

答案 1 :(得分:0)

尝试类似这样的事情

function compareAge($date,$min=18)
{
    $strdate = strtotime($date);
    $curdate = strtotime("today");
    $datefin=date("Ymd",$curdate)-date("Ymd",$strdate);
    $age=substr($datefin,0,strlen($datefin)-4);
    return $age>=$min;
}

var_dump(compareAge("2013-05-13"));

DEMO

答案 2 :(得分:0)

你可以使用这种方法:

public function validateAge($then)
{
  $then= date_create($then);
  $now = date_create("now");

  $diff = $now->diff($then);

  if ($diff->y > 18)
  {
  die('not 18');
  }

}

重复: Calculating number of years between 2 dates in PHP

答案 3 :(得分:0)

使用datetime对象来保存各种痛苦。它简单得多。

function validateAge(DateTime $then, $min = 18)
{
    $now = new DateTime();

    $minimum = clone($now);         // you could just modify now, but this is simpler to explain
    $minimum->modify("-$min years");


    if($then < $minimum) {
        return false;
    } 

    return true;
}

echo validateAge(new DateTime('1-1-1997')) ? 'true' : 'false';  // returns false
echo validateAge(new DateTime('1-1-1999')) ? 'true' : 'false';  // returns true

请参阅example

答案 4 :(得分:0)

哇,这么多的努力。 万一你喜欢很简单:

<?php
function validateAge($date) {
    return date_create('18 years ago') > date_create($date);
}

var_dump(
    validateAge('2010-10-05'),
    validateAge('1992-09-02')
);

<强>输出

bool(false)
bool(true)

Play with me on 3v4l.org

修改:还可以使用$ min参数:

<?php
function validateAge($date, $min) {
    return date_create("$min years ago") > date_create($date);
}

var_dump(
    validateAge('2010-10-05', 18),
    validateAge('1992-09-02', 18)
);