Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I access DateTime->date in PHP's DateTime class?

Tags:

php

datetime

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.

like image 630
okey_on Avatar asked Dec 29 '12 17:12

okey_on


People also ask

How do you use DateTime class?

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.

How can I get current date in dd mm yyyy format in PHP?

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: " .

How can I get current date and time in PHP?

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.


1 Answers

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'); 
like image 139
jeremy Avatar answered Oct 02 '22 02:10

jeremy