Adi
Adi

Reputation: 301

How can I compare a date with current date using Doctrine 2?

I have a database where an "expiry date" is stored. Now I want the current date with the stored expiry date compared. If the current date is before the expiry date, the data should be displayed like usual, but if the data is expired, I want it to be excluded.

I tried:

$query = $em->createQuery('SELECT d FROM test d WHERE d.expDate > :date')
    ->setParameters('date', 'now()');

Help would be cool, or some tips if someone understands my problem.

Upvotes: 22

Views: 57014

Answers (4)

Vojtech Adam
Vojtech Adam

Reputation: 54

Actually, your way does work but you have a small error in your code.

You use:

$query = $em->createQuery('SELECT d FROM test d WHERE d.expDate > :date')
->setParameters('date', 'now()');

Now you can change by two ways so that it works: 1. Leave the "s" at "setParameters"-> set Parameter

Or

  1. Use array when using "parameters", in your case:

    $query = $em->createQuery('SELECT d FROM test d WHERE d.expDate > :date')
     ->setParameters(array('date' => 'now()');

Upvotes: 3

Uzair Bin Nisar
Uzair Bin Nisar

Reputation: 705

You can use the date function to create a string to be compared:

$query = $em->createQuery('SELECT d FROM test d');
$query->addWhere("d.exp_date > ?",date("Y-m-d", time()));

Upvotes: 2

fain182
fain182

Reputation: 1075

There is another way:

$query = $em->createQuery('SELECT d FROM test d WHERE d.expDate > :today')
    ->setParameter('today', new \DateTime())->

Upvotes: 35

Crozin
Crozin

Reputation: 44396

Right now, you're comparing expDate column to the text "now()", not to the result of the function now().

$em->createQuery('SELECT d FROM test d WHERE d.expDate > CURRENT_DATE()');

Upvotes: 20

Related Questions