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 the 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\TH:i:s', 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.

Drupal 8 - Date field database
Drupal 8 - Date field database

If I can be of assistance, please do not hesitate to contact me.

About the author

Goran Nikolovski is a highly experienced Drupal developer with an extensive skill set that includes PHP, MySQL, HTML, CSS and Javascript. He has experience with large Drupal sites and Drupal Commerce 2.x integration, and he is author of several Drupal modules.