Edy
Edy

Reputation: 11

Date Instructions in Symfony 3.3

I am new on dates with Symfony. I try to use the PHP website instructions in my Symfony 3.3 Controller, and I can't get an answer. For example, I want to add 10 days to my date. In the web: http://php.net/manual/en/datetime.add.php Php sugests this way:

<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>

I used the first two lines in my Symfony 3.3 Controller:

namespace Food\FruitBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    public function addAction()
    {
      $date = new DateTime('2000-01-01');
      $date->add(new DateInterval('P10D'));
      return new Response($date);
    }

I got this mistake:

Attempted to load class "DateTime" from namespace "Food\FruitBundle\Controller".
Did you forget a "use" statement for "Symfony\Component\Validator\Constraints\DateTime"?

Then I add the use instruction:

Now it shows this mistake:

"No default option is configured for constraint Symfony\Component\Validator\Constraints\DateTime"

How can I use a DateTime instruction, such as add? Thanks!

Upvotes: 0

Views: 2080

Answers (1)

dbrumann
dbrumann

Reputation: 17166

The message:

Attempted to load class "DateTime" from namespace "Food\FruitBundle\Controller". Did you forget a "use" statement for "Symfony\Component\Validator\Constraints\DateTime"?

tells you that it tries to load a classDateTime from your current namespace, but the class is part of the global namespace. There are 2 possible solutions. Either you prefix the class with a \ to signify you want the class from the global namespace. So it could like this:

$date = new \DateTime('2000-01-01');

or you can write a use DateTime; in the top of the file to tell php that every time that new DateTime actually refers to the global class and not one in your current namespace.

You might still have an issue afterwards when you try to pass the object into the response as it might not render the date correctly. That's because new Response($date) will try to make this object into a string by calling it's magic __toString() method. It's similar to doing echo (string) $date or simply echo $date. This will use a default format that might not fit your needs. That's why you should use the format()-method instead as seen in your first snippet. So it could look like this:

return new Response($date->format('Y-m-d'));

Upvotes: 4

Related Questions