gpt4 book ai didi

php - Symfony/Doctrine Dateinterval(持续时间)如何将其存储在数据库中

转载 作者:可可西里 更新时间:2023-10-31 22:12:33 25 4
gpt4 key购买 nike

我有一个问题,我正在编写一个有某种服务预订的应用程序。该服务有一个持续时间,例如:

A massage that takes 1 hour and 15 minutes

然后我为这项服务做一个预订系统。在进行预订时,我需要计算结束日期时间。

所以我的数据库中有一个“开始”日期时间,但我不知道如何存储持续时间。所以在预订之后我可以很容易地说这将在其他日期时间结束。

希望我说得足够清楚。

问题是如何在数据库中存储持续时间以及如何增加开始日期,所以我对时区等没有任何问题。

感谢您的帮助!

最佳答案

一种只使用PHP(不使用SQL)的方法,时间以秒为单位以简化计算:

$reservation = new Reservation(); // Your entity object

$startDate = new \DateTime('now');
$endDate = $startDate;
$endDate->modify('+'.4500.' seconds'); // Update the end time with the duration of the service

$reservation->setStartDate($startDate);
$reservation->setEndDate($endDate);

// Save the reservation
$em = $this->getDoctrine()->getManager();
$em->persist($reservation);
$em->flush();

编辑 1:

要回答您的时区问题,最简单的(我认为)是使用时间戳!在显示时,时间戳将转换为时区日期。从日期时间获取时间戳时,它是相同的,它是根据机器的时区计算的。所以时间戳在时区之间共享^^

这里是编辑的片段:

// ...

// Save timestamp instead of datetime
$reservation->setStartTimestamp($startDate->getTimestamp());
$reservation->setEndTimestamp($endDate->getTimestamp());

// ...

编辑 2:

要回答您的评论,如果您更改了持续时间,只需将持续时间保存在数据库中即可。

// First save
$reservation->setDuration(4000); // seconds

并且在编辑持续时间时:

// Duration of a reservation change

// <- Load the $reservation to edit

$date = new \DateTime();
$date->setTimestamp($reservation->getStartTimestamp()); // Got start date

$reservation->setDuration($reservation->getDuration() + 2000); // For example, duration is increased of 2000 second

$endDate = $date;
$endDate->modify('+'.$reservation->getDuration().' seconds'); // Use start date and recalculate new end date
$reservation->setEndTimestamp($endDate->getTimestamp());

// <- Then update $reservation with a persist

关于php - Symfony/Doctrine Dateinterval(持续时间)如何将其存储在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16883223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com