Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare Dates from database in Yii2

Tags:

yii2

$time = new \DateTime('now');
$today = $time->format('Y-m-d');
$programs=Programs::find()->where(['close_date' >= $today])->all();

This is code for today's programs whose close_date is greater than today's date. I am getting error:

"Invalid Parameter -yii\base\InvalidParamException Operator '1' requires two operands".

like image 664
Sujata Avatar asked Feb 12 '15 05:02

Sujata


People also ask

How to match 2 dates in PHP?

Example: <? php $date1 = new DateTime("18-02-24"); $date2 = new DateTime("2019-03-24"); if ($date1 > $date2) { echo 'datetime1 greater than datetime2'; } if ($date1 < $date2) { echo 'datetime1 lesser than datetime2'; } if ($date1 == $date2) { echo 'datetime2 is equal than datetime1'; } ?>

Can I compare dates in PHP?

Comparing two dates in PHP is simple when both the dates are in the same format but the problem arises when both dates are in a different format. Method 1: If the given dates are in the same format then use a simple comparison operator to compare the dates. echo "$date1 is older than $date2" ; ?>


2 Answers

If you want to write where condition as array the code should be like this:

$programs = Programs::find()->where(['>=', 'close_date', $today])->all();

Check official documentation for more details:

Additionally you can specify arbitrary operators as follows: A condition of ['>=', 'id', 10] will result in the following SQL expression: id >= 10.

like image 73
arogachev Avatar answered Oct 05 '22 21:10

arogachev


Or like this code:

$programs = Programs::find()->where('close_date >= :close_date', [':close_date' => $today])->all();
like image 41
vitalik_74 Avatar answered Oct 05 '22 23:10

vitalik_74