how to use php DateTime() function in Laravel 5
PhpLaravelLaravel 5Php Problem Overview
I am using laravel 5. I have try to use the
$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?
Php Solutions
Solution 1 - Php
DateTime
is not a function, but the class.
When you just reference a class like new DateTime()
PHP searches for the class in your current namespace. However the DateTime
class obviously doesn't exists in your controllers namespace but rather in root namespace.
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();
Solution 2 - Php
Best way is to use the Carbon dependency.
With Carbon\Carbon::now();
you get the current Datetime.
With Carbon you can do like enything with the DateTime. Event things like this:
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
Solution 3 - Php
If you just want to get the current UNIX timestamp I'd just use time()
$timestamp = time();
Solution 4 - Php
I didn't mean to copy the same answer, that is why I didn't accept my own answer.
Actually when I add use DateTime
in top of the controller solves this problem.