I'm developing a module where I have to set a user profile date_field. I tried several methods to implement this but not one worked for me.
This is the code I am using.
private function updateUser($user_import,$uid = null) {
if (!$uid) {
return false;
}
$roles = $this->matchRoles($user_import->roles);
$birthday = $this->birthdayDate($user_import->profile_geburtsdatum);
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$user = \Drupal\user\Entity\User::load($uid);
// $user->setPassword($this->randomPassword());
$user->setEmail($user_import->mail);
$user->setUsername($user_import->name);
$user->enforceIsNew(false);
// Optional settings
$user->set("init", $user_import->init);
$user->set("langcode", $language);
$user->set("preferred_langcode", $language);
$user->set("preferred_admin_langcode", $language);
foreach ($roles as $role) {
$user->addRole($role);
}
$user->set("field_profile_geburtsdatum", array('#default_value' => $birthday));
$user->activate();
$user->save();
drupal_set_message("UPDATE: User " . $user_import->name . ' ( '. $user_import->mail . ')');
}
private function birthdayDate($import_date) {
$date = null;
if (!empty($import_date)) {
$date = strtotime($import_date->day.'.'.$import_date->month.'.'.$import_date->year);
$date = date('Y-m-d 00:00:00',$date);
$date = new \Drupal\Core\Datetime\DrupalDateTime($date, 'Europe/Berlin');
/* $date = array(
'year' => date('Y',$date),
'month' => date('m',$date),
'day' => date('d',$date),
);
*/
}
return $date;
}