猿问

如何在 PHP 中按时间间隔显示列表

如何在 PHP 中按时间间隔显示列表


例如:特定日期的 00: 00 至 15: 30。我这样尝试:


我在同一天从00:00开始花了15小时30分钟。这个想法是显示这些时间之间的列表。我有什么错吗?


$todayMidday = new \DateTime('now');

$todayMidday->sub(new \DateInterval('PT15H30M'));


return $this->createQueryBuilder('b')

    ->andWhere('b.reservationDate <= :today')

    ->andWhere('b.reservationDate >= :today')

    ->orderBy('b.hours', $order)

    ->setParameter('today', $todayMidday->format('Y-m-d'))

    ->setMaxResults($limit)

    ->getQuery()

    ->getResult();


智慧大石
浏览 83回答 1
1回答

慕仙森

您的代码有很多问题。因为你是新人,所以我会尽力提供帮助。我不知道为什么这个问题被标记下来。到目前为止的两条评论与您的问题并不真正相关。这里的一个问题是在 \DateTime 中使用“sub”,而且事实上你只有 1 个 \DateTime 对象。最后,当您查询数据库时,您完全节省了时间。“sub”函数从日期中减去间隔。所以你的代码所说的是:“获取当前日期和时间,然后从中减去 15 小时 30 分钟,现在选择所有小于或等于和大于或等于今天日期的记录(忽略时间)”您想要的是有 2 个 \DateTime 对象,一个用于结束时间,一个用于开始时间。例如://get the current date time$timeFrom = new \DateTime();//now set the time to 00:00$timeFrom->setTime(0,0,0);//get the current date time$timeTo = new \DateTime();//now set the time to 00:00$timeTo->setTime(15,30,0);return $this->createQueryBuilder('b')&nbsp; &nbsp; ->andWhere('b.reservationDate <= :timeTo')&nbsp; &nbsp; ->andWhere('b.reservationDate >= :timeFrom')&nbsp; &nbsp; ->orderBy('b.hours', $order)&nbsp; &nbsp; ->setParameter('timeTo', $timeTo->format('Y-m-d H:i:s'))&nbsp; &nbsp; ->setParameter('timeFrom', $timeFrom->format('Y-m-d H:i:s'))&nbsp; &nbsp; ->setMaxResults($limit)&nbsp; &nbsp; ->getQuery()&nbsp; &nbsp; ->getResult();当然有多种不同的方法来设置日期/时间,但要注意的关键点是 1 个 \DateTime 对象一次只能保存 1 个日期和时间。您可以按任意时间间隔更改该日期或时间,但它只会保留 1 个新时间。它没有范围。
随时随地看视频慕课网APP
我要回答