2

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

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

What is wrong with this code?

2
  • Are you sure the code is called? What function is this code within?
    – acrosman
    Jul 22 '16 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 '16 at 2:02
6

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',
]);
$account->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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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