0

This is my code:

$date1 = new DateTime();
$date1->format('Y-m-d H:i:s');
echo $date1->date. ' while echoing date1';  

It echoes only " while echoing date1", in other words $date1->date is empty.
If I add dump date1 first like this:

$date1 = new DateTime();
$date1->format('Y-m-d H:i:s');
var_dump($date1);
echo $date1->date. ' while echoing date1';  

I get

object(DateTime)[359]
  public 'date' => string '2016-06-26 16:54:56.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'UTC' (length=3)

2016-06-26 16:54:56.000000 while echoing date1

which is what I want. This thing is getting me mad as it is completely unexpected.

Ferex
  • 535
  • 6
  • 22

1 Answers1

2

The format option isn't for setting the format of the object, it's a method that returns the date object as a string in the requested format:

echo $date->format('Y-m-d H:i:s');

To clarify, what you see as a 'date' within the object is just a text representation for convenience, as internally it will be held in an optimized way. If you want to add it to a string, you need to specify the format you want:

echo "This is the date ".$date->format('c');
WhoIsRich
  • 3,943
  • 1
  • 32
  • 19