Home > Software engineering >  Saving Y-m-d to Datetime to DateTimeImmutable field in Symfony
Saving Y-m-d to Datetime to DateTimeImmutable field in Symfony

Time:01-18

I want to save Y-m-d date format to field date

#[ORM\Column]
private ?\DateTimeImmutable $created_at = null;

When I save this formatted date:

$date = new DateTimeImmutable();
$date->setTimestamp($timestamp);
$date->format("Y-m-d");

Symfony saves with the following format:

2023-01-17 14:34:55

When I try to save a date like this:

$date = date("Y-m-d", $timestamp);

I get an error:

must be of type DateTimeImmutable, string given

What am I missing?

CodePudding user response:

There are two problems that play a role here:

1: your entity expects an DateTimeImmutable Object, but you provide a string. Thus to solve this, use The DateTimeImmutable object to create and pass the correct object type your method asks for.

2: You want to save your date in a specific format, Y-m-d. To do that, change your ORM\Column type to date instead of dateTime

If you want to use Y-m-d format in your project, use the correct formatting to achieve that.

Take a look at the docs for deeper understanding.

CodePudding user response:

To save the date in Y-m-d Format, you can use createFromFormat method

$date = DateTimeImmutable::createFromFormat("Y-m-d", date("Y-m-d", $timestamp));

I hope it will solve your problem. Let me know if you have any question

  • Related