2012-02-06 48 views
1

我想在Yii编写一个验证规则,但无法获得日期比较工作。如果End不大于过去Start的30天,则想要显示错误消息。日期加上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!'); 
+0

小心使用strtotime来验证e用户输入见[strtotime Php手册](http://php.net/manual/en/function.strtotime.php)'时间戳的有效范围通常是从1905年12月13日星期五20:45:54 UTC到星期二,2038年1月19日03:14:07 UTC.'如果你可以使用php [日期时间](http://www.php.net/manual/en/class.datetime.php) – Henesnarfel 2012-02-06 18:47:10

+0

介意解释为什么和/或给出选择? – enfield 2012-02-06 18:47:56

回答

4

如果你compairing $duration$this->END(其中来自右出的数据库),你需要把你date('Y-m-d', $duration)核对$this->END 你compairing一个的strtotime到date('Y-m-d')哪里都是苹果和桔子

更改 $ duration = strtotime(date('Ym-d',strtotime($ this-> Start))。'+30 days'); 到 $ duration = date('Y-m-d',strtotime($ this-> START。'+ 30 days'));

和你的脚本应该工作

希望这有助于

+0

这是用于验证用户输入的表单。所以我试图验证用户输入,而不是数据库内容。 – enfield 2012-02-06 18:46:31

+0

您的线路: $ duration = strtotime(date('Y-m-d',strtotime($ this-> Start))。'+30 days'); 返回一个unix时间戳 如果您将其转换为YYYY-MM-DD,则时间戳将始终更大 – AMayer 2012-02-06 18:52:06

+0

感谢您的输入,我编辑了我的问题以显示更改和结果。总是显示错误。 – enfield 2012-02-06 19:20:26

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'); 
+0

感谢您的输入,我编辑了我的问题以显示更改和结果。不知道我是否正确使用它,但页面不会呈现,并且日志不显示原因。 – enfield 2012-02-06 19:21:46

+0

'var_dump($ interval); $ days_diff = $ interval-> d; echo $ days_diff;' – cetver 2012-02-06 19:25:48

+0

也注意属性'invert' – cetver 2012-02-06 19:31:09

0

您可能需要使用DateTime->diff和检查天的差值小于30则触发错误

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"); 
    } 
} 
+0

不是我在这种情况下寻找的东西,但在许多其他情况下非常有帮助。我会好好利用它。 – enfield 2012-02-07 16:40:32