我正在尝试在 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!');
最佳答案
如果您正在将 $duration
与 $this->END
(直接从数据库中获取)进行比较,您需要将 date('Y-m- d', $duration)
在检查 $this->END
之前
您正在将 strtotime 与 date('Y-m-d')
进行比较,其中苹果和橘子
改变 $duration = strtotime(date('Y-m-d', strtotime($this->Start)) . '+30 天'); 到 $duration = date('Y-m-d', strtotime($this->START . '+ 30 days'));
你的脚本应该可以运行
希望对你有帮助
关于php - 日期加 30 天验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9165318/