dongwei3172 2018-08-16 11:03
浏览 92
已采纳

Doctrine 2.2 Symfony 3.4中的日期时间字符串转换

I am troubleshooting a search bar to return rows within a period chosen from 'To' and 'From' datepickers.

I initially got this error :

Error: Method Doctrine\ORM\Query\Expr\Comparison::__toString() must not throw an exception, caught Symfony\Component\Debug\Exception\ContextErrorException: Catchable Fatal Error: Object of class DateTime could not be converted to string

I converted the relevant query to a string using ->format() function:

            if (is_array($value) && isset($value['to'])) {

            $to = \DateTime::createFromFormat('d/m/Y H:i:s', $value['from'] . ' 23:59:59');
            var_dump($value, $to);die;
            if ($to <> false) {
                $query->andWhere(
                        $query->expr()->lte($path, $to->format('Y-m-d H:i:s'))
                );
            }
        }

Now doctrine throws the following error:

[Syntax Error] line 0, col 977: Error: Expected end of string, got '00'

Is there something else I need to do to format the date to make it acceptable to the querybuilder? I've tried using / instead of : but this causes an issue.

  • 写回答

1条回答 默认 最新

  • dqwd71332 2018-08-16 12:47
    关注

    If I recall correctly, you should either use literal(), or query parameter. And since the lte argument is not constant, using literal() is highly discouraged (due to potential SQL injection).

    Anyway, something like this should probably work:

    if (is_array($value) && isset($value['to'])) {

    if (is_array($value) && isset($value['to'])) {
    
        $to = \DateTime::createFromFormat('d/m/Y H:i:s', $value['from'] . ' 23:59:59');
    
        if ($to <> false) {
            $query->andWhere($query->expr()->lte($path, ':to'));
            $query->setParameter('to', $to->format('Y-m-d H:i:s'));
        }
    }
    

    Does it work?

    Hope it helps...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题