0
<?
foreach ($results as $data) {
  $date = $data->created;
  $now = new DateTime();
  echo $date->diff($now)->format(" %y years,%d days, %h hours and %i minuts");
?>

I used this code to fetched date from mysql table and print it in codeigniter framework view file. And my mysql date type is "timestamp". So can you please help me to print the difference between today and the fetched date from mysql table. error msg-Call to a member function diff() on string -- and got this message after using this code

Dhananjana
  • 45
  • 1
  • 7
  • Possible duplicate of [How to calculate the difference between two dates using PHP?](https://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – pr1nc3 Feb 07 '18 at 13:51
  • You can do this also in your mysql query – pr1nc3 Feb 07 '18 at 13:55

2 Answers2

2

You have to convert your created value into a DateTime. The timestamp value from your database looks like "2018-02-02 05:08:32". The constructor of DateTime could convert it. So, you have just to wrap your value using new DateTime() :

$date = new DateTime($data->created);
$now = new DateTime();
echo $date->diff($now)->format(" %y years,%d days, %h hours and %i minuts");
Syscall
  • 19,327
  • 10
  • 37
  • 52
0

you need to transform your timestamp into a DateTime object before you can diff:

$date = new DateTime();
$date->setTimestamp($data->created);
Ali
  • 3,568
  • 2
  • 24
  • 31