Question

How to calculate the time difference between two datetime fields. Here I want to find time difference of ept.endedTime and ept.startedTime.

$query = $em->createQuery('SELECT t.code, t.name, t.description, ept.endedTime, ept.startedTime, DATE_DIFF(ept.endedTime, ept.startedTime)'
. ' FROM AdrotecCompanyBundle:EmployeeProjectTask ept'
. ' JOIN ept.task t'
. ' JOIN ept.employeeProject ep'
. ' JOIN ep.employee e'
. ' WHERE ep.project = :pId');
Was it helpful?

Solution

Use this to write a user defined dql function then use it.

<?php
class DateDiff extends FunctionNode
{
    // (1)
    public $firstDateExpression = null;
    public $secondDateExpression = null;

    public function parse(\Doctrine\ORM\Query\Parser $parser)
    {
        $parser->match(Lexer::T_IDENTIFIER); // (2)
        $parser->match(Lexer::T_OPEN_PARENTHESIS); // (3)
        $this->firstDateExpression = $parser->ArithmeticPrimary(); // (4)
        $parser->match(Lexer::T_COMMA); // (5)
        $this->secondDateExpression = $parser->ArithmeticPrimary(); // (6)
        $parser->match(Lexer::T_CLOSE_PARENTHESIS); // (3)
    }

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        return 'DATEDIFF(' .
            $this->firstDateExpression->dispatch($sqlWalker) . ', ' .
            $this->secondDateExpression->dispatch($sqlWalker) .
        ')'; // (7)
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top