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