php 如何使用 Doctrine 2 将日期与当前日期进行比较?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10582108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:31:06  来源:igfitidea点击:

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

phpsymfonydoctrine-orm

提问by Adi

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.

如果有人理解我的问题,帮助会很酷,或者一些提示。

回答by fain182

There is another way:

还有一种方法:

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

回答by Crozin

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

现在,您将expDatecolumn 与文本“now()”进行比较,而不是与 function 的结果进行比较now()

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

回答by Uzair Bin Nisar

You can use the datefunction to create a string to be compared:

您可以使用该date函数创建要比较的字符串:

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

回答by Vojtech Adam

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

现在您可以通过两种方式进行更改以使其正常工作: 1. 将“s”保留在“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()');
  1. 在使用“参数s”时使用数组,在您的情况下:

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