Set value to datetime field

Datetime fields with Drupal 8 are tricky. Two actions are needed:
  • Format the time into UTC.
  • Format the time into datetime format.
<?php
 
/**
   * Format the string date into datetime.
   *
   * @param string $string
   *   String value.
   *
   * @return string
   *   Datetime value.
   */
 
public function strToDate($string) {
    try {
     
$date = new \DateTime($string, new \DateTimeZone(drupal_get_user_timezone()));
     
$date->setTimezone(new \DateTimeZone('UTC'));

      return
$date->format('Y-m-d\TH:i:s');
    }
    catch (\
Exception $e) {
      return
0;
    }
  }
?>