Using the DateTime
class, if I try to run the following code:
$mydate = new DateTime(); echo $mydate->date;
I'll get back this error message
Notice: Undefined property: DateTime::$date...
Which doesn't make sense because when running var_dump()
on the variable $mydate
, it clearly shows that this property exists and is publicly accessible:
var_dump($mydate); object(DateTime)[1] public 'date' => string '2012-12-29 17:19:25' (length=19) public 'timezone_type' => int 3 public 'timezone' => string 'UTC' (length=3)
Is this a bug within PHP or am I doing something wrong? I'm using PHP 5.4.3.
To use the DateTime object you just need to instantiate the the class. $date = new DateTime(); The constructor of this object takes two parameters the first is the time value you want to set the value of the object, you can use a date format, unix timestamp, a day interval or a day period.
php /*print date in dd/mm/yy format*/ print "Current date in dd/mm/yy format: " . date("d/m/y"); print "</br>"; /*print date in dd/mm/yyyy format*/ print "Current date in dd/mm/yyyy format: " . date("d/m/Y"); print "</br>"; /*print date in dd MON yyyy format*/ print "Current date in dd MON yyyy format: " .
Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date('d-m-y h:i:s') , date('d/m/y H:i:s') , and so on.
This is a known issue.
Date being available is actually a side-effect of support for
var_dump()
here – [email protected]
For some reason, you're not supposed to be able to access the property but var_dump
shows it anyways. If you really want to get the date in that format, use the DateTime::format()
function.
echo $mydate->format('Y-m-d H:i:s');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With