PHP有效的DOB输入/不准确的日期比较

PHP有效的DOB输入/不准确的日期比较,php,validation,date,yii,Php,Validation,Date,Yii,我使用的是Yii框架,在修改数据时为模型验证设置一些规则。其中之一是比较有效的DOB输入。标准为DOB不应为 比今天更伟大 从今天起的100年之间 以下是我实施规则的方式: /** * Checks the valid input for DOB * * @return boolean * @throws Error Message */ public function validDOB($attribute,$params){ if (($bdate = $this->

我使用的是Yii框架,在修改数据时为模型验证设置一些规则。其中之一是比较有效的DOB输入。标准为DOB不应为

  • 比今天更伟大
  • 从今天起的100年之间
  • 以下是我实施规则的方式:

    /**
     * Checks the valid input for DOB
     *
     * @return boolean
     * @throws Error Message
     */
    public function validDOB($attribute,$params){
        if (($bdate = $this->bdate) != null){               
            $now = new DateTime("now");
            $dob = DateTime::createFromFormat('d/m/Y', $bdate);
            $interval = $now->diff($dob);
    
            $curdate=strtotime($now->format('d/m/Y'));
            $largedate=strtotime($dob->format('d/m/Y'));
    
            if ($interval->y > 100){
                $this->addError('bdate', 'Wow! Are you sure you are ' . $interval->y .' years old?');
            }elseif ($curdate > $largedate){
                $this->addError('bdate', 'Psst.. Hey... You are not a time traveller...');
            }
        }
    }
    
    所以问题是,当选择了无效日期时,验证器假设有效并抛出错误,但是,假设今天的日期是2014年9月3日(d/m/Y),而选择的日期是2014年9月4日(d/m/Y),假设系统应该提示错误消息,但它作为有效输入返回。我必须选择日期,直到2014年9月13日左右(d/m/Y),然后只有系统显示无效输入

    年度选择也是如此。假设该日期为2014年9月13日(d/m/Y),那么在100年之间,这意味着如果用户在1914年9月13日(d/m/Y)之前选择任何内容,系统将提示无效。。。但它也会导致上面这样的错误

    此外,我还意识到,当我使用strotime()来比较未来的日期时,不知何故会导致100年之间的年份也变得无效


    我做错了什么

    为什么在比较之前要格式化
    DateTime
    对象?您可以按原样比较
    DateTime
    实例。@NDM对不起?您是如何按原样比较日期时间实例的?您可以比较
    $now
    $dob
    ,而不必使用
    strotime($date->format(“…”)
    $now>$dob
    。另外,从
    DateTime
    对象转换为字符串,然后解析该字符串作为时间戳是不必要的: