Default value for datetime field definition in content entity? I have the following datetime field definition for my content entity:

$fields['start_date'] = BaseFieldDefinition::create('datetime')
  -&gt;setLabel(t('Start date'))
  -&gt;setDescription(t('Start date in GMT time.'))
  -&gt;setSettings([
    'default_value' =&gt; DrupalDateTime::createFromTimestamp(time()),
  ])
  -&gt;setDisplayOptions('view', [
    'label' =&gt; 'above',
    'type' =&gt; 'string',
    'weight' =&gt; -4,
  ])
  -&gt;setDisplayOptions('form', [
    'type' =&gt; 'datetime_default',
    'weight' =&gt; -3,
  ])
  -&gt;setDisplayConfigurable('form', TRUE)
  -&gt;setDisplayConfigurable('view', TRUE);


As a result, when creating a new entity, I get the field display without default value set in a form. I also tried setDefaultValue method but with no luck.
What is the proper way to set the default values for the custom content entities?
You need to pass in a callback function that is evaluated when the entity is saved. If you evaluate the time value in YourEntity::baseFieldDefinitions, then the default value will fixed at whatever time the entity type was installed.

DrupalDateTime::createFromTimestamp can't serve as a callback because it expects you to pass a timestamp. The default value callback needs to take two arguments: the entity being saved and the field definition itself:


\Drupal\Core\Entity\FieldableEntityInterface $entity
\Drupal\Core\Field\FieldDefinitionInterface $definition


See the API docs: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21FieldConfigInterface.php/function/FieldConfigInterface%3A%3AsetDefaultValueCallback/8.7.x

So you'll need to create a callback function, e.g.

use Drupal\datetime\Plugin\Field\FieldType\DateTimeItem;

// ...

function mymodule_get_current_datetime($entity, $definition) {
  $current_time = DrupalDateTime::createFromTimestamp(time());
  return $current_time-&gt;format(DateTimeItem::DATETIME_STORAGE_FORMAT);
}



And then pass that callback as a string.

$fields['start_date'] = BaseFieldDefinition::create('datetime')
  -&gt;setLabel(t('Start date'))
  -&gt;setDescription(t('Start date in GMT time.'))
  -&gt;setDefaultValueCallback('mymodule_get_current_datetime')
  -&gt;setDisplayOptions('view', [
    'label' =&gt; 'above',
    'type' =&gt; 'string',
    'weight' =&gt; -4,
  ])
  -&gt;setDisplayOptions('form', [
    'type' =&gt; 'datetime_default',
    'weight' =&gt; -3,
    'default_value' =&gt; DrupalDateTime::createFromTimestamp(time()),
  ])
  -&gt;setDisplayConfigurable('form', TRUE)
  -&gt;setDisplayConfigurable('view', TRUE);