Datetime column from mysql database rendered as String in PHP
I am using multiple arrays p1, p2. Their third parameter is the datetime taken from the mysql database. When I try to find the difference between these dates, a warning appears:Warning: date_diff() expects parameter 1 to be DateTimeInterface, string given in ...
Here is the code:
$format = "Y-m-d H:m:s";
$t1 = strtotime($p1[2]);
$time1 = date($format,$t1);
$t2 = strtotime($p2[2]);
$time2 = date($format,$t2);
$diff = date_diff($time1, $time2);
New edit This is how I take datetime from db:
$temp=array();
foreach ($arr_smp as $column => $context) {
if($column == "latitude" || $column == "longitude" || $column == "date_time")
{
array_push($temp,$context);
}
where $context
is lat or lon or date_time
You can help? Thanks in advance!
source to share
As stated in the error message, you are also writing this value from the database table as a string. So you need to convert them to object DateTime()
and then get the difference. Please see: -
<?php
$p1[2] = "2015-10-10"; // i assume that $p1[2] is like this
$p2[2] = "2015-10-12"; // i assume that $p2[2] is like this
$t1 = new DateTime($p1[2]); //conversion into date-time object
$t2 = new DateTime($p2[2]); //conversion into date-time object
$diff = date_diff($t1, $t2); // get difference
echo "<pre/>";print_r($diff); // print difference
?>
Output: - https://eval.in/388744
source to share
There are several errors in this code, firstly, your format is not valid:
$format = "Y-m-d H:m:s";
Indicates hours, months and seconds if you need several minutes (you can blame months and minutes for this):
$format = "Y-m-d H:i:s";
Second problem: date_diff doesn't accept strings as input, so your error correlates with the arguments you supplied too. I would rewrite your code like this:
$dateOne = new Datetime($p1[2]);
$dateTwo = new Datetime($p2[2]);
$dateDiff = $dateOne->diff($dateTwo);
var_dump($dateDiff);
Then you can use the date diff object to find the date difference values.
Enjoy.
source to share