Search code examples
phpdatetimevar-dump

PHP DateTime Class Producing Unexpected Results


I have been getting used to the DateTime Class and am getting unexpected results from the code below:

<?php  
  $now =  date("Y-m-d H:i:s");
  echo $now .'</br>';
  $newDate = date("Y-m-d H:i:s",strtotime("$now + 1 years"));
  $converted = strtotime("$newDate");
  $outputDate = new DateTime("@$converted");
  var_dump($outputDate);
  echo "Output - ". $outputDate->date;
?>

When I have the var_dump($outputDate) I get the expected output (i.e. the Output string is at the end):

2015-03-29 23:08:30
object(DateTime)#1 (3) { ["date"]=> string(26) "2016-03-29 21:08:30.000000"   
["timezone_type"]=> int(1) 
["timezone"]=> string(6) "+00:00" } Output - 2016-03-29 21:08:30.000000

However when I have the exact same code and comment out var_dump($outputDate):

<?php  
  $now =  date("Y-m-d H:i:s");
  echo $now .'</br>';
  $newDate = date("Y-m-d H:i:s",strtotime("$now + 1 years"));
  $converted = strtotime("$newDate");
  $outputDate = new DateTime("@$converted");
  // var_dump($outputDate);
  echo "Output - ". $outputDate->date;
?>

I just get:

2015-03-29 23:14:13
Output -

I am not sure why having the var_dump($outputDate) line allows me to output the date. I have resolved the issue using a different approach but I am curious to why this is the case. Any suggestions?


Solution

  • date property is not defined in Datetime class docs so this behavior is undefined and you can't rely on such code. For getting your datetime represented as string you should use format() method like this:

    echo "Output - ". $outputDate->format("Y-m-d H:i:s");
    //or with procedural style
    echo "Output - ". date_format($outputDate,"Y-m-d H:i:s");
    

    You can read more about possible format parameters on PHP docs.