Add time to date and time with PHP

Asked

Viewed 131 times

2

Good morning.

I did extensive research before asking, and I couldn’t find the answer.

$row['data_saida'] = "2019-06-20";
$row['hora_saida'] = "08:35:02";

These two strings come from the database, returning the separate date and time (as shown above), but would like to generate a prediction based on another string, which returns from the database. That is to say:

$row['data_saida'] = "2019-06-20";
$row['hora_saida'] = "08:35:02";
$row['tempo_viagem'] = "02:30:02";

I would add 02:30:02 with 2019-06-20 08:35:02, to get the arrival forecast.

2 answers

2


You can perform this operation with the class Datetime together with the Dateinterval

$row['data_saida'] = "2019-06-20";
$row['hora_saida'] = "08:35:02";
$row['tempo_viagem'] = "02:30:02";

$saida = sprintf('%s %s', $row['data_saida'], $row['hora_saida']);

$data  = new DateTime($saida);
$data->add(new DateInterval("P0000-00-00T{$row['tempo_viagem']}"));

$chegada = $data->format('Y-m-d H:i:s');

// Chegada com data pt-BR
//$chegada = $data->format('d/m/Y H:i:s');

echo $chegada;

See this fiddle (Click the button RUN F9)

  • Thank you! Helped a lot. : D

0

You must use strtotime() with the date and time string followed by the range you want to add. That is, to add time, minute and second would have to follow the date and time with '+X hours +Y minutes +Z seconds'. To do this you can manipulate the duration string that comes from the database as in the example below:

$data = '2019-06-20';
$hora = '08:35:02';
$duracao = '02:30:02';

$data_hora= $data.' '.$hora ; 
$duracao = vsprintf(" +%d hours +%d minutes +%d seconds", explode(':', $duracao)); 

print date('Y-m-d H:i:s',strtotime($data_hora.$duracao));

See working: http://sandbox.onlinephpfunctions.com/code/6207ff0ca1897f5c1443be549c923548020e22a6

  • Perfect my noble. Thank you! D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.