25

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.

slick1537
  • 745
  • 2
  • 8
  • 19

2 Answers2

58

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

$time = new \DateTime('now', new \DateTimeZone('UTC'));
John Conde
  • 217,595
  • 99
  • 455
  • 496
2

Add use for DateTime:

use Yii;
use DateTime;

See use "global-namespace";

Anton Rybalko
  • 1,229
  • 17
  • 23