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

1.1k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

6
On

DateTime (and DateTimeImmutable) has a modify method which you could leverage to modify the time by adding 20 hours and 20 minutes.

Updated

I've included examples for both DateTime and DateTimeImmutable as per the comment made, you don't need to assign the outcome of modify to a variable because it mutates the original object. Whereas DateTimeImmutable creates a new instance and doesn't mutate the original object.

DateTime

<?php

$start = new DateTimeImmutable('2018-10-23 00:00:00');
echo $start->modify('+20 hours +20 minutes')->format('Y-m-d H:i:s');

// 2018-10-23 20:20:00

Using DateTime: https://3v4l.org/6eon8

DateTimeImmutable

<?php

$start = new DateTimeImmutable('2018-10-23 00:00:00');
$datetime = $start->modify('+20 hours +20 minutes');

var_dump($start->format('Y-m-d H:i:s'));
var_dump($datetime->format('Y-m-d H:i:s'));

Output

string(19) "2018-10-23 00:00:00"

string(19) "2018-10-23 20:20:00"

Using DateTimeImmutable: https://3v4l.org/oRehh