CodeIgniter Forums
DateTime php function causing error - Printable Version

+- CodeIgniter Forums (
+-- Forum: CodeIgniter 4 (
+--- Forum: CodeIgniter 4 Support (
+--- Thread: DateTime php function causing error (/showthread.php?tid=76549)

DateTime php function causing error - kick - 05-24-2020

I am trying to get the difference between two dates and wanted to use the basic date->diff function of the DateTime class in php, however the error I am receiving from CodeIgniter 4.0.3 is that it can't find the DateTime class in my controllers directory. Here is what I am doing:

PHP Code:
$date1 = new DateTime($dobStr);
$date2 $date1->diff(new DateTime(date('m/d/Y',time())));


Has anyone gotten this error if so what have you done to get around it? Thanks in advance.

I found a way around it by turning it into a helper method.

I would still appreciate it if anyone know how/why declaring a new PHP native class would cause CI4 to look for it within it's calling class directory and if there is other ways of accomplishing the calls to native classes.

RE: DateTime php function causing error - dave friend - 05-24-2020

It's probably a namespace issue. Make sure to specify the "global" namespace for the DateTime class by preceding it with a \

PHP Code:
$date1 = new \DateTime($dobStr);  \\see the backslash
$date2 $date1->diff(new \DateTime(\date('m/d/Y', \time())));


RE: DateTime php function causing error - Zakawa - 05-25-2020

You eather need to add a backslash at every DateTime reference, or you can just add a use statement (after the namespace).

PHP Code:
use \DateTime

RE: DateTime php function causing error - kilishan - 05-25-2020

As they said, it's a namespace issues. If your controller is namespaced as App\Controllers, then any new class you try to instantiate will assume it's in App\Controllers, also, which DateTime obviously isn't. So you have to tell PHP to look for it in the root namespace, by prefixing with the backslash.

Additionally - CI4 provides a new Time class that can do what you're wanting to do, and more.