Drupal - Programmatically set a datetime field

Datetime fields in Drupal 8 are stored as strings. So you need to convert it into string.

You can use the format method, e.g.

$formatted_date = $date->format('Y-m-d H:i:s');

Refer Inserting the value from Datetime field form

You can also use T as separator,

Like:

\DateTime::format("Y-m-d\TH:i:s"); //need a escape character in front of T.

Refer Why is my Datetime field not saved?


If your date field is not a DATETIME but a DATE, use a different format. And a better solution would be to use the Datime object constant to get the format.

constant DATETIME_STORAGE_FORMAT :: string(12) "Y-m-d\TH:i:s"
constant DATE_STORAGE_FORMAT :: string(5) "Y-m-d"

Working example.

$dtime = DateTime::createFromFormat("m/d/Y - G:i", $row->Date); // not needed
$dtime->setTimezone(new \DateTimezone(DateTimeItemInterface::STORAGE_TIMEZONE));
$dtimeFormat = $dtime->format(DateTimeItemInterface::DATE_STORAGE_FORMAT);

$article->set('field_date', $dtimeFormat);

This is what worked for me:

$timestamp = \Drupal::time()->getRequestTime();
$date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
$entity->field_date = $date->format("Y-m-d\TH:i:s");

Tags:

Nodes

8