-2

i am trying to find difference between two dates in php, the first date is coming from my database (which is in datetime format), so i am converting it to date and then finding the difference using the current date. my code is like below:

$ret=mysqli_query($con,"select * from members");
$cnt=1;
while ($row=mysqli_fetch_array($ret))
{
  $date_time = $row['date'];
  $new_date = date("Y-m-d",strtotime($date_time));
  $dates = date('Y-m-d');
  $diff = $new_date->diff($dates);

  echo $diff;
}

then i am getting the following error:

Uncaught Error: Call to a member function diff() on string in C:\xampp\htdocs\form\admin\members.php:123 Stack trace: #0 {main} thrown in C:\xampp\htdocs\form\admin\members.php on line 123

can anyone please tell me what i am doing here is wrong. thanks in advance

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Does this answer your question? [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Jens Feb 03 '20 at 07:55

3 Answers3

1

date function returns a string. https://www.php.net/manual/en/function.date.php

You can use date_diff function to compare dates in string format https://www.php.net/manual/en/function.date-diff.php

or use DateTime class which has method diff. https://www.php.net/manual/en/class.datetime.php

Magiczne
  • 1,586
  • 2
  • 15
  • 23
0

Use date_diff function instead of the object notation here, DateTime object if you want your date to be Object

ROOT
  • 11,363
  • 5
  • 30
  • 45
0

date() function returns a string. You need to create an object of DateTime class. Your loop should look something like this:

foreach ($ret as $row) {
    $new_date = new \DateTime($row['date']);
    $diff = $new_date->diff(new \DateTime());

    var_dump($diff);
}
Dharman
  • 30,962
  • 25
  • 85
  • 135