Symfony/Doctrine日期间隔(时间持续时间)如何将其存储在数据库中


Symfony/Doctrine Dateinterval (time duration) how to store it in database

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

1小时15分钟的按摩

那么我为这项服务做了一个预订系统。当我做预订时,我需要计算结束日期时间。

所以我有一个Datetime在我的数据库为"开始",我不知道如何存储持续时间。因此,在预订之后,我可以很容易地说,它将在其他日期结束。

我希望我说得够清楚了。

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

谢谢你的帮助!

一种只使用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:

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

下面是编辑过的代码片段:
// ...
// 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

除了Sybio的回答之外,您还可以为预订期间设置time数据类型。那么Doctrine将接受'DateInterval的一个实例。

$reservation
    ->setStartDate(new 'DateTime('now'))
    ->setDuration('DateInterval::createFromDateString('75 minutes'))
;

然后在控制器中,你可以这样做:

$em = $this->getDoctrine()->getManager();
$reservation = $em->getRepository('AcmeMassageParlorBundle:Reservation')->find($id);
// The instance has to be cloned before being modified, to avoid accidentally
// altering the start time.
$endDate = clone $reservation->getStartDate();
$endDate->add($reservation->getDuration());
// To get the date time in ISO format, use
$endDate->format('Y-m-d H:i:s');