I am trying to set the value of a user field which is a date. If i check the database, the date is in this format:


I have the user ID and a new Unix timestamp value that I want to overwrite the existing value with.

The following shows no error messages but does not change the date

$account = \Drupal\user\Entity\User::load($email_result); // pass your uid

//$field = $account->field_expiry_date;
//$field = $account->get('field_expiry_date');

What is wrong with this code?

  • Are you sure the code is called? What function is this code within?
    – acrosman
    Jul 22, 2016 at 21:25
  • Positive. It's directly underneath a database insert (to a different table) and a drupal_set_msg, both of which work. The function is within a public function submitForm on a Config Form Jul 23, 2016 at 2:02

1 Answer 1


The problem is more than likely that the 'c' format includes the timezone, which is not (currently) included in storage.

The storage format for fields that have both date and time is defined by the datetime module as DateTimeItemInterface::DATETIME_STORAGE_FORMAT, which is 'Y-m-d\TH:i:s'.

Something like this will work:

use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\user\Entity\User;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;

$date = DrupalDateTime::createFromTimestamp($new_expiry, 'UTC');
$account = User::load($email_result);
$account->field_expiry_date->value = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, [
  'timezone' => 'UTC',

Just remember that date+time values in storage are implicitly UTC, so if you are setting the value manually, you need to ensure that what you are saving represents what you want, but converted to UTC.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.