Search code examples
phpdatetimedateinterval

How to correctly add a date and a time (string) in PHP?


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?


Solution

  • If you want to add 20 hours and 20 minutes to a DateTime:

    $date = new \DateTime('17.03.2016');
    $date->add($new \DateInterval('PT20H20M'));
    

    You do not need to get the result of add(), calling add() on a DateTime object will change it. The return value of add() is the DateTime object itself so you can chain methods.

    See DateInterval::__construct to see how to set the intervals.