Convert the difference between dates to string

2

I'm calculating in PHP the difference between datetimes (start, end), coming from a POST , need to fill a campo(time) in format(H:i:s) via INSERT in MYSQL .

I get the result of the difference, but I can not use it because when I do the insert I get an error saying that the difference field is not converted to string :

  

Error: "(Object of class DateInterval could not be converted to   string) ".

If it is an error of string same, how do I do the conversion? Is there any other way to do this in PHP ?

$inicio = new DateTime($data_inicio); 
$fim   = new DateTime($data_fim);

$duracao = $inicio->diff($fim);
$duracao = $duracao->format('%h:%i:%s');

$sql = "INSERT into horarios VALUES ('$duracao')";

Thank you for your ever-present partnership

P.S .: If you already have this question clarified in another post inform me, but I checked first and I'm beating myself a lot.

    
asked by anonymous 04.10.2016 / 23:04

3 answers

3

One possibility, using simple and integer subtraction:

$date1 = strtotime( '10/04/2016 15:03' );
$date2 = strtotime( '10/04/2016 16:28' );

$duracao = date( 'H:i:s', abs( $date2 - $date1 ) );

// Aqui usa o valor como necessitar:
$sql = "INSERT INTO horarios VALUES ('$duracao')";

See working at IDEONE .

Important Note that when the date is separated by traits , PHP already interprets as DD-MM-AAAA , and with forward as MM/DD/AAAA . If you need to, you can change it like this:

strtotime(str_replace('/', '-', '11/04/2016 18:10'));


If you need to compare the time difference with the current date

Just instead of using strtotime( "$data $hora" ); , opt for one of these functions

$date2 = mktime(); // Use essa se quiser hora local
$date2 = time();   // Ou essa se quiser UTC
    
05.10.2016 / 04:02
2

Hugo, make sure your field in the database is time or something, from php version 5.6 it is possible that the time objects talk directly to the database, please, if your table is in string which is not recommended, you should explore the DateInterval object format it to string and add it to the database, if you can not and if you want, you can also use the library Chronus .

    
05.10.2016 / 03:34
0

Use with date_diff:

$differenceFormat = "%H:%i:%s"

$datetime1 = date_create($data_inicio);
$datetime2 = date_create($data_fim);

$interval = date_diff($datetime1, $datetime2);

$sql = "INSERT into horarios VALUES ('$interval->format($differenceFormat);')";
    
04.10.2016 / 23:38