code: public static function dateTimeString($datetime)
      {
          if ($datetime === null) {
              return null;
          }
  
          if (is_object($datetime) && !($datetime instanceof \DateTime)) {
              throw new \Exception('Only \DateTime objects allowed');
          }
  
          if (is_string($datetime)) {
              $datetime = new \DateTime($datetime);
          }
  
          return $datetime->format("Y-m-d\TH:i:s.uP");
      }
docs: Convert datetime from string or \DateTime object to ATOM string
  
  @param string|\DateTime $datetime
  @throws \Exception
  @return null|string