如何在 Laravel 5 中使用 php DateTime() 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30708711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use php DateTime() function in Laravel 5
提问by Praveen Srinivasan
I am using laravel 5. I have try to use the
我正在使用 Laravel 5。我尝试使用
$now = DateTime();
$timestamp = $now->getTimestamp();
But it shows error likes this.
但它显示这样的错误。
FatalErrorException in ProjectsController.php line 70:
Call to undefined function App\Http\Controllers\DateTime()
What Can I do?
我能做什么?
回答by Limon Monte
DateTimeis not a function, but the class.
DateTime不是函数,而是类。
When you just reference a class like new DateTime()PHP searches for the class in your current namespace. However the DateTimeclass obviously doesn't exists in your controllers namespace but rather in root namespace.
当您只引用像new DateTime()PHP这样的类时,会在您当前的命名空间中搜索该类。但是,DateTime该类显然不存在于您的控制器命名空间中,而是存在于根命名空间中。
You can either reference it in the root namespace by prepending a backslash:
您可以通过在根命名空间中添加反斜杠来引用它:
$now = new \DateTime();
Or add an import statement at the top:
或者在顶部添加导入语句:
use DateTime;
$now = new DateTime();
回答by Praveen Srinivasan
Best way is to use the Carbondependency.
最好的方法是使用Carbon依赖项。
With Carbon\Carbon::now();you get the current Datetime.
随着Carbon\Carbon::now();你的当前日期时间。
With Carbon you can do like enything with the DateTime. Event things like this:
使用 Carbon,您可以使用 DateTime 做任何事情。像这样的事件:
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
回答by Crembo
回答by Praveen Srinivasan
I didn't mean to copy the same answer, that is why I didn't accept my own answer.
我不是故意复制相同的答案,这就是为什么我没有接受我自己的答案。
Actually when I add use DateTimein top of the controller solves this problem.
实际上,当我use DateTime在控制器顶部添加时解决了这个问题。

