Set date field programmatically

Set date field programmatically

Date fields in Drupal 8 are stored as strings in the database, with a maximum length of 20 characters [ varchar(20) ].

You can configure the date field to hold only date value. In that case the value is stored as a string like this 2020-12-31

Or you can configure the date field to hold both date and time. In that case the value is stored as a string like this 2020-12-31T23:59:59

On the other hand, values for base fields created and changed are stored as integers [ int(11) ]. All content entities have these values and they indicate when the content was created and updated. These values look something like this 1473344734

Let's see how to programmatically set date field values.

use Drupal\node\Entity\Node;

// Set specific values.
$node = Node::load(1);
$node->set('field_date', '2025-12-31');
$node->set('field_datetime', '2025-12-31T23:59:59');
$node->set('created', '1760140799');
$node->save();
use Drupal\node\Entity\Node;

// Set the current date and time.
$node = Node::load(1);
$node->set('field_date', date('Y-m-d', time()));
$node->set('field_datetime', date('Y-m-d\T00:00:00', time()));
$node->set('created', time());
$node->save();

Additional note

If you take a look at the database table of your date field, you will see that time zone is not stored. That's because dates in Drupal 8 are stored in the UTC timezone.

You may also like

An alternative to Menu Token module

As of writing this blog post, Menu Token module for Drupal 8 is still in the alpha version and it might not work in all cases. That's why having an alternative solution is great. The alternative to using Menu Token module for Drupal 8 is to use Menu link plugins.

2018 recap

As this year draws to an end and another one is only 24 hours away, I reflect on the best things that happened to me.