PHPLover
PHPLover

Reputation: 12957

How to resolve this error "Catchable fatal error: Object of class DateTime could not be converted to string in /var/www/web/print.php on line 9"?

I want to show error message if the date in a specific variable is greater than today's date. For it I wrote following code but it's gigiving the error: "Catchable fatal error: Object of class DateTime could not be converted to string in /var/www/web/print.php on line 9"

<?php
  error_reporting(E_ALL);
  ini_set('display_errors', '1');
  $form_data['trans_date'] = '12-11-2014';
  $newTransDate = DateTime::createFromFormat('!m-d-Y', $form_data['trans_date']);
  $today_date = new DateTime();
  echo "Trans Date " . $newTransDate; die; //This is line no.9
  if($newTransDate > $today_date)
    echo "Error";
  else
    echo "Success";  
?>

What modifications need to be done to the above code in order to function everything with proper comparison of two dates?

Upvotes: 0

Views: 92

Answers (2)

Kevin
Kevin

Reputation: 41875

You need to use ->format() on that created DateTime object if your intent is to get the date that you want.

echo "Trans Date " . $newTransDate->format('Y-m-d'); // and remove that die!

Upvotes: 2

Pupil
Pupil

Reputation: 23958

Because,

echo "Trans Date " . $newTransDate; die; //This is line no.9

$newTransDate is an object and your printing it with echo, a function dedicated to print string.

You can print it with:

echo '<pre>';
print_r($newTransDate);
echo '</pre>';

echo

print_r()

Upvotes: 0

Related Questions