Welcome Guest, Not a member yet? Register   Sign In
DateTime php function causing error
#1

(This post was last modified: 05-24-2020, 11:27 AM by kick.)

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())));

echo 
$date2->y

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.
Reply
#2

(This post was last modified: 05-26-2020, 06:06 AM by dave friend.)

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())));

echo 
$date2->y
Reply
#3

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
Reply
#4

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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB