Set the value of a date field 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:

2016-06-30T07:52:51

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
$account-&gt;set('field_expiry_date',strval(date('c',($new_expiry))));

//$field = $account-&gt;field_expiry_date;
//$field-&gt;set(date('c',($new_expiry)));
//$field = $account-&gt;get('field_expiry_date');
//$field-&gt;setValue(date('c',($new_expiry)));


What is wrong with this code?
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-&gt;field_expiry_date-&gt;value = $date-&gt;format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, [
  'timezone' =&gt; 'UTC',
]);
$account-&gt;save();


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.