0

I upgraded a Craft 2 project to Craft 3 and am working on updating some template quirks. One I am having trouble with involves the following element query:

{% set scriptsAboutToExpire = craft.entries({
    section: 'scripts',
    order: 'expirationDate asc',
    expirationDate: [ 'and', '>=' ~ now, '<=' ~ now|date_modify('+2 weeks') ]
}) %}

This worked great in Craft 2. It grabs all script entries whose expirationDate field is two weeks away from today's date.

However now after upgrading to Craft 3 I am getting the following error when viewing that template:

PHP Recoverable Error – yii\base\ErrorException Object of class DateTime could not be converted to string

with a highlight on this line:

(isset($context["now"]) || array_key_exists("now", $context) ? $context["now"] : (function () { throw new Twig_Error_Runtime('Variable "now" does not exist.', 10, $this->source); })())), 2 => ("<=" . twig_date_modify_filter($this->env, (isset($context["now"]) || array_key_exists("now", $context) ? $context["now"] : (function () { throw new Twig_Error_Runtime('Variable "now" does not exist.', 10, $this->source); })()), "+2 weeks"))))), "method");

I tried updating all .localeDate() filters to |date('short') but that had no effect.

1

Please read the docs

 'now'|date() 

Is what you want usually formatted as timestamp date('U') or as mysql datetime format date('Y-m-d H:i:s')

  • While it no longer complains that now is empty, after modifying now in my element query to 'now'|date(), it still is saying "Object of class DateTime could not be converted to string." $context["scriptsAboutToExpire"] = array("section" => "scripts", "order" => "expirationDate asc", "expirationDate" => array(0 => "and", 1 => (">=" . $this->extensions['craft\web\twig\Extension']->dateFilter($this->env, "now")), 2 => ("<=" . twig_date_modify_filter($this->env, $this->extensions['craft\web\twig\Extension']->dateFilter($this->env, "now"), "+2 weeks")))); – Steven Thate Apr 23 '18 at 19:54
  • 1
    As I said "usually formatted as a timestamp or mysql datetime" it's all stated in the docs and in my answer. You have to convert the DateTime object into a valid sql string format – Robin Schambach Apr 23 '18 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.