Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set datetime field in the symphony 3 for update or insert data?

Tags:

php

symfony

I am trying to set the date and time field in the symfony 3.4 in this way:

$eventProject = new $eventProject();

$eventProject->setDateFrom('2018-05-09');

when I save the values, It is giving me error like:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'dateFrom' can
  not be null
In ConversionException.php line 95:

  Could not convert PHP value '2018-05-09' of type 'string' to type 'datetime
  '. Expected one of the following types: null, DateTime

I could not understand what is wrong ?

like image 226
flik Avatar asked Dec 17 '22 23:12

flik


1 Answers

You need to use PHP's DateTime object to set the date.

$eventProject = new $eventProject();
$date = new \DateTime('2018-05-09');
$eventProject->setDateFrom($date);

This also means that you have to work with DateTime when retrieving the date.

$date = $eventProject->getDate();
var_dump($date->format("Y-m-d")); 
//string(10) "2018-05-09"

Be sure to use format on a retrieved DateTime object when you want to get the date as a string.

This is more about how the eventProject class/entity is written and not something that is forced by Symfony. That being said it is quite a common way to work with time in PHP projects. In the beginning it can seem a little awkward but as you get used to it you will find DateTime to be pretty handy.

like image 146
hcoat Avatar answered Jan 05 '23 00:01

hcoat