获取与日期的日期时间差

时间:2018-12-17 09:21:54

标签: doctrine symfony4 doctrine-query

嗨,我正在尝试提供一些天数,并获取从那天到现在的记录。

            $now = new \DateTime();
            $days = 14;
            $to = $now->sub(new \DateInterval('P'.$days.'D'));
            $qb = $this->createQueryBuilder('c')
            $qb->andWhere('c.createdDate BETWEEN :from AND :to')
                    ->setParameter('from', $now)
                    ->setParameter('to', $to);
            $qb->getQuery()->getResult();

在我的数据库 created_date 列中,并有一条记录包含2018-12-12。但是不幸的是查询没有返回值:(。如果有人可以解决,这将是非常有帮助的。而且我正在使用sub来获取减日期。

1 个答案:

答案 0 :(得分:2)

有效查询是:

$from = new \DateTime('-14 days');
$to = (new \DateTime())->setTime(23, 59, 59);

$qb = $this->createQueryBuilder('c')
$qb->andWhere('c.createdDate BETWEEN :from AND :to')
    ->setParameter('from', $from)
    ->setParameter('to', $to);

$result = $qb->getQuery()->getResult();

它对您不起作用的原因是因为\DateTime是可变类型。通过更改副本,您还更改了上一个日期对象:

$from = new \DateTime();

// below you mutate the $from object, then return its instance
$to = $from->sub(new \DateInterval('P10D'));
// effect is both $from and $to reference the same object in memory

var_dump(spl_object_hash($from) === spl_object_hash($to));
echo $from->format('Y-m-d') , '<br>';
echo $to->format('Y-m-d');

将导致:

bool(true) 
2018-12-07
2018-12-07

您在“ Doctrine”中将属性createdDate映射为datetime。我个人总是使用datetime_immutable类型。我使用DateTimeImmutable代替了DateTime,与DateTime相比,它在设计上是不可变的,因此我不必担心任何引用:

$from = new \DateTimeImmutable();
$to = $from->sub(new \DateInterval('P10D'));

var_dump(spl_object_hash($from) === spl_object_hash($to));
echo $from->format('Y-m-d') , '<br>';
echo $to->format('Y-m-d');

结果:

bool(false)
2018-12-17
2018-12-07