Marciohrm
Marciohrm

Reputation: 11

How to add time to a datetime in php

There is two fields in a table, one is datetime and the other is time. I need to create a new datetime adding the field time to the datetime to compare with current date.

$time = $table['date'] + $table['time'];

date is 2019-08-08 01:15:00 time is 00:05:00 I would like to receive 2019-08-08 01:20:00

How can I solve this?

Upvotes: 1

Views: 68

Answers (2)

jspit
jspit

Reputation: 7703

If you can use a DateTime extension class like dt

$table['date'] = '2019-08-08 01:15:00';
$table['time'] = '00:05:00';

$dt = dt::create($table['date'])->addTime($table['time']);

echo $dt->format('Y-m-d H:i:s');  //2019-08-08 01:20:00

Upvotes: 0

Nick
Nick

Reputation: 147166

PHP doesn't have an easy way of adding a time to a date. One way is to convert the date and time to DateTime objects; compute the difference between the time and midnight; and then add that to the date:

$table['date'] = '2019-08-08 01:15:00';
$table['time'] = '00:05:00';

$date = new DateTime($table['date']);
$time = new DateTime('00:00:00');
$interval = $time->diff(new DateTime($table['time']));
$date->add($interval);
echo $date->format('Y-m-d H:i:s');

Output:

2019-08-08 01:20:00

Demo on 3v4l.org

Upvotes: 1

Related Questions