Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add minutes to PHP Datetime to calculate start/end of event

I would like to calculate with PHP the start and end datetime of an event. I get the start of this event and the duration to add to get the end. So I tried the following code:

$startTime = $this->getStartTime();
$endTime = $this->getStartTime();

$endTime->add(new DateInterval('PT75M'));

in this example I add 75 minutes to the start time and I calculate the end of the event. It works, however it edits also the start time. I read in the PHP docs that the ADD method edits the object which is called on but I don't understand how it could edit the startEdit variable. I don't use reference in any of the methods that I wrote in the example, neither in the getStartTime function

like image 386
Stefano Avatar asked Dec 08 '12 19:12

Stefano


People also ask

How can I add minutes and minutes in PHP?

For this, you can use the strtotime() method. $anyVariableName= strtotime('anyDateValue + X minute'); You can put the integer value in place of X.

How to get minutes Difference in PHP?

$min += $interval ->h * 60; $min += $interval ->i; // Printing the Result in Minutes format. echo ( "Difference in minutes is: " );

How to use date_ add in PHP?

Example. <? php //Creating a DateTime object $date = date_create("25-09-1989"); //Adding interval to the date $res = date_add($date, new DateInterval('PT10H30S')); //formatting the date to print it $format = date_format( $res, "d-m-Y H:i:s"); print($format); ?>

How to echo date time in PHP?

echo "The time is " . date("h:i:sa"); ?> Note that the PHP date() function will return the current date/time of the server!


1 Answers

You have to create a new DateTime instance for that or you will be editing your original reference to your start date DateTime object. Try something like this:

$endTime = clone $startTime;
$endTime->add(new DateInterval('PT75M'));
like image 159
Benjamin Paap Avatar answered Sep 29 '22 13:09

Benjamin Paap