What is the "cleanest" way to add a date and a time string in PHP?
Albeit having read that DateTime::add
expects a DateInterval
, I tried
$date = new \DateTime('17.03.2016');
$time = new \DateTime('20:20');
$result = $date->add($time);
Which was no good and returned nothing to $result
.
To make a DateInterval
from '20:20'
, I only found very complex solutions...
Maybe I should use timestamps?
$date = strtotime($datestring);
$timeObj = new \DateTime($timestring);
// quirk to only get time in seconds from string date
$time = $timeObj->format('H') * 3600 + $timeObj->format('i') * 60 + $timeObj->format('s');
$datetime = $date+$time;
$result = new \DateTime;
$result->setTimestamp($datetime);
In my case, this returns the desired result, with the correct timezone offset. But what do you think, is this robust? Is there a better way?
If you want to add 20 hours and 20 minutes to a
DateTime
:You do not need to get the result of
add()
, callingadd()
on aDateTime
object will change it. The return value ofadd()
is theDateTime
object itself so you can chain methods.See DateInterval::__construct to see how to set the intervals.