【问题标题】:Get datetime difference with doctrine使用学说获取日期时间差异
【发布时间】:2019-05-17 15:21:15
【问题描述】:

您好,我正在尝试给出从那天到现在的天数并获取记录。

            $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 来获取减日期。

【问题讨论】:

  • created_date 字段在数据库中的类型为 datetimedate?试试$to = (new \DateTime(sprintf('+%d days', $days)))->setTime(23, 59, 59);
  • 日期字段,我也试过日期时间
  • 你知道两者之间是有区别的。你应该知道你在做什么,而不是盲目地改变类型,希望它能起作用。

标签: doctrine symfony4 doctrine-query


【解决方案1】:

有效的查询是:

$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

【讨论】:

  • 非常感谢兄弟的精彩解释和很好的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-18
  • 1970-01-01
  • 2023-03-26
  • 2013-05-18
  • 1970-01-01
  • 2013-09-30
  • 1970-01-01
相关资源
最近更新 更多