日期加上30天验证

时间:2012-02-06 18:37:43

标签: php mysql validation yii

我正在尝试在Yii中编写验证规则,但无法将日期与工作进行比较。如果End不超过Start之后的30天,则要呈现错误消息。

public function checkDate($attribute,$params)
    {
        $duration = strtotime(date('Y-m-d', strtotime($this->Start)) . ' +30 days');
        if ($this->End < $duration) 
                $this->addError('End','30 days or more!');
    }

这样每个输入都会产生错误信息。我正在使用MySql数据库,而开始和结束是date格式

修改 鉴于以下答案中的输入,我试过了

现在甚至不会呈现页面。

    $startDate = $this->Start;
    $endDate = $this->End;
    $interval = $startDate->diff($endDate);
    if ($interval < 30) 
                $this->addError('End','30 days or more!');

这会在100%的时间内产生错误。

$duration = date('Y-m-d', strtotime($this->Start . '+ 30 days'));
if ($this->End < $duration) 
    $this->addError('End','30 days or more!');

4 个答案:

答案 0 :(得分:4)

如果您正在$duration$this->END(直接来自数据库),则需要在检查date('Y-m-d', $duration)之前添加$this->END 你正在把一个strtotime改为date('Y-m-d')哪里有苹果和橘子

变化 $ duration = strtotime(date('Y-m-d',strtotime($ this-&gt; Start))。'+ 30天'); 至 $ duration = date('Y-m-d',strtotime($ this-&gt; START。'+ 30天'));

并且您的脚本应该正常工作

希望这会有所帮助

答案 1 :(得分:2)

#source: http://www.php.net/manual/en/datetime.diff.php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

答案 2 :(得分:0)

您可能需要使用DateTime->diff并检查天数之差是否小于30然后触发错误

答案 3 :(得分:0)

我已经按照以下方式使用它了:

public function rules()
{
    return array(
    ...
        array('dateX','timeoutSomething'),
    ...
    );
}


public function timeoutSomething($dateX){
    // If you try to modify the model after 300 seconds the error arise
    if((strtotime($this->dateX)+300) < time()){
        $this->addError($dateX,"Timeout exceed");
    }
}
相关问题