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!');
if you are compairing
$durationto$this->END(which comes right out of the database) you need to putdate('Y-m-d', $duration)before you check against$this->ENDyou’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