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.

2 Answers 2

59

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

$time = new \DateTime('now', new \DateTimeZone('UTC'));
Sign up to request clarification or add additional context in comments.

2 Comments

Don't forget \DateTimeZone
Awesome answer thanks. I don't completely understand namespaces it is a new concept to me.
2

Add use for DateTime:

use Yii;
use DateTime;

See use "global-namespace";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.