日期加 30 天验证
我正在尝试在 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 数据库,开始和结束是日期格式
编辑: 鉴于下面答案中的输入,我已经尝试过
,现在甚至不会渲染页面。
$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!');
I am trying to write a validation rule in Yii but can't get the date compare to work. Looking to render the error message if End
is not greater than 30 days past Start
.
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!');
}
With this every input yields the error message. I am using a MySql db and Start and End are date
format
EDIT:
Given the input in the answers below I have tried
This will not even render the page now.
$startDate = $this->Start;
$endDate = $this->End;
$interval = $startDate->diff($endDate);
if ($interval < 30)
$this->addError('End','30 days or more!');
and
This gives the error 100% of the time.
$duration = date('Y-m-d', strtotime($this->Start . '+ 30 days'));
if ($this->End < $duration)
$this->addError('End','30 days or more!');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您要将
$duration
与$this->END
(直接来自数据库)进行比较,则需要输入date('Ymd', $持续时间)
,然后再检查$this->END
您正在将 strtotime 与
date('Ymd')
进行比较,其中苹果和橙子发生了变化
$duration = strtotime(date('Ymd', strtotime($this->Start)) . ' +30 天');
到
$duration = date('Ymd', strtotime($this->START . '+ 30 天'));
你的脚本应该可以工作
希望这有帮助
if you are compairing
$duration
to$this->END
(which comes right out of the database) you need to putdate('Y-m-d', $duration)
before you check against$this->END
you're compairing a strtotime to a
date('Y-m-d')
where are apples and orangeschange
$duration = strtotime(date('Y-m-d', strtotime($this->Start)) . ' +30 days');
to
$duration = date('Y-m-d', strtotime($this->START . '+ 30 days'));
and your script should work
hope this helps
您可能需要使用 DateTime->diff 并检查是否存在差异天数小于 30 则触发错误
You may want to use DateTime->diff and check if the difference of days is less 30 then trigger an error
我已经通过以下方式使用它:
I'm already using this in the following way: