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

new*_*icz 4 php database symfony doctrine-orm

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

按摩需要1小时15分钟

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

所以我在数据库中有一个“开始”的日期时间,而且我不知道如何存储持续时间。因此,预订后我可以轻松地说这将在其他日期时间结束。

我希望我足够清楚。

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

感谢帮助!

Syb*_*bio 5

仅使用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();
Run Code Online (Sandbox Code Playgroud)

编辑1:

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

此处的片段已编辑:

// ...

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

// ...
Run Code Online (Sandbox Code Playgroud)

编辑2:

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

// First save
$reservation->setDuration(4000); // seconds
Run Code Online (Sandbox Code Playgroud)

当编辑持续时间时:

// 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
Run Code Online (Sandbox Code Playgroud)