How to set date field programmatically

Introduction

Important things to keep in mind when it comes to Drupal 8 Date fields:

  • The core Date field is stored as a string [ varchar(20) ] in the database and gives you the option to store:
    • the date only: 2021-12-31
    • or the date with time: 2021-12-31T23:59:59
  • The Timestamp field is stored as an int [ int(11) ] in the database and represents a the Unix time.
  • Drupal 8 stores all date fields in the UTC timezone. Timezone information is not stored with the date fields.

Setting date values programmatically

Assume that $node has the following fields:

  • field_date: Date field (date only)
  • field_datetime: Date field (date and time)
  • field_timestamp: Timestamp field

Here is one way to set the field values programmatically:

// Set dates to arbitrary values
$node->set('field_date', '2021-12-31');
$node->set('field_datetime', '2021-12-31T22:00:00');
$node->set('field_timezone', '1596663532');

// Set dates to current time
$node->set('field_date', date('Y-m-d', time()));
$node->set('field_datetime', date('Y-m-d\TH:i:s', time()));
$node->set('field_timezone', time());