I want to save Y-m-d date format to field date
#[ORMColumn]
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?
2
Answers
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
There are two problems that play a role here:
1: your entity expects an
DateTimeImmutable
Object, but you provide astring
. Thus to solve this, use TheDateTimeImmutable
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 ORMColumn type to
date
instead ofdateTime
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.