Trying to use PHP DateTime Class with Yii2 receiving class not found errors

slick1537 picture slick1537 · May 6, 2014 · Viewed 25k times · Source

Hello I am trying to create my own custom helper class to use with Yii2. It is going to handle times so I'll be working with PHP's DateTime class. I have

<?php

namespace yii\helpers;

use Yii;

class Time
{
    public static function getTime()
    {  
    $time = new DateTime('now', new DateTimeZone('UTC'));
    return $time->format('m-d-Y H:i:s');
    }
}

To test it I added use yii\helpers\Time; to a view file and called Time::getTime(); but Yii2 throws an ErrorException saying Class 'yii\helpers\DateTime' not found.

The php DateTime object works fine if I place the code directly into a view file and execute it so I'm not sure what my problem is.

Answer

John Conde picture John Conde · May 6, 2014

Put a backslash in from of the class name to indicate it is in the global namespace:

$time = new \DateTime('now', new \DateTimeZone('UTC'));