Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DateTime class Namespace

I'm using the symfony2 framework and I want to use the PHP's DateTime class (PHP version is 5.3).

Here the declaration:

namespace SDCU\GeneralBundle\Entity;  class Country {    public function __construct(){        $this->insertedAt = new DateTime();    } } 

But, when executing this constructor, I get an error saying that there's no "SDCU\GeneralBundle\Entity\DateTime" class. I've been searching around for DateTime's namespace but with no success... any idea?

like image 423
Miguel Ribeiro Avatar asked Dec 03 '11 12:12

Miguel Ribeiro


People also ask

How to use DateTime class in PHP?

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.

What is new DateTime in PHP?

The DateTime::format() function is an inbuilt function in PHP which is used to return the new formatted date according to the specified format.

What Date Time PHP function will I use if I want to calculate the date 30 days from today?

echo date('m/d/Y',strtotime('+30 days',strtotime('05/06/2016'))) .


2 Answers

DateTime is in the global namespace, and as "class names always resolve to the current namespace name" you have to use \DateTime.

Or import the package using:

use \Datetime; 
like image 89
str Avatar answered Oct 23 '22 14:10

str


Better solution for using classes in global namespaces is "use" keyword instead of "\" before class.

namespace SDCU\GeneralBundle\Entity; use \DateTime;  class Country {    public function __construct(){        $this->insertedAt = new DateTime();    } } 
like image 35
Glavić Avatar answered Oct 23 '22 15:10

Glavić