Inserting the value from Datetime field form I have a form where the user can input datetime and then I want to store it in the database. Here's my schema :


  'start' => array(
          'type' => 'varchar', 'mysql_type' => 'datetime',
          'not null' => FALSE,
        ),


The form :


  $form['add']['start'] = array(
        '#type' => 'datetime',
  '#default_value' => $date,
      );


When I hit submit button, it shows me :


  db_insert failed. Message = SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value:...


What I got out of it was that the DateTime in Drupal is incompatible with MySQL's. Any suggestions or how should I process the value from the form so I can insert it into the db?

Alternatively, any way to convert DrupalDatetime into string?

(For what it's worth I also tried 'timestamp' as the MySQL type but it throws me the same error).
Datetime fields in Drupal 8 are stored as strings, partially because date support between databases isn't consistent and partially to make them easy to manipulate to extract parts where there aren't proper date functions.

The date is stored with the format DATETIME_DATETIME_STORAGE_FORMAT, and the timezone is implicitly DATETIME_STORAGE_TIMEZONE.

You would need to do something like:

Before Drupal 8.5

/** @var \Drupal\Core\Datetime\DrupalDateTime $date */
$date-&gt;setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));
$string = $date-&gt;format(DATETIME_DATETIME_STORAGE_FORMAT);


In Drupal 8.5 and after, as per https://www.drupal.org/node/2912980

/** @var \Drupal\Core\Datetime\DrupalDateTime $date */
$date-&gt;setTimezone(new \DateTimezone(DateTimeItemInterface::STORAGE_TIMEZONE));
$string = $date-&gt;format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);


There are better ways to handle this, though.  It is best to use the date formatter service to format the dates, rather than the ::format() method (I'm being lazy here).  It is also probably best to use proper entities and add this as a field, and not just stuff it into a database table.