Drupal Datetime in Custom Module (convert Europe/Germany to UTC)

Problem:

Timezone of Server/PHP/Drupal : Europe/Germany

Datetime value converted automatically to UTC + 120 Minutes (Europe/Germany). 

Solution:

Convert Datetime to UTC before saving node. 

PHP Code (modules/custom/my_module/src/Controller/MyController1.php):

<?php

use Drupal\node\NodeInterface;
use Drupal\node\Entity;
use Drupal\node\Entity\Node;
use Drupal\Core\Datetime;
use Drupal\Core\DateTimeZone;

// ... other code, class, function etc
    
    
$datum_obj = \DateTime::createFromFormat('d.m.Y H:i', "29.08.2024 14:15");


$datum_obj->setTimezone(new \DateTimeZone( 'UTC' ) );
$datum_uhrzeit = $datum_obj->format("Y-m-d\TH:i:s");

// $datum_timestamp = $datum_obj->getTimestamp();

$node = Node::create([
    'type' => 'article',
    'langcode' => 'de',
    'title' =>  "Some Custom Title",
    'field_my_custom_date' =>  $datum_uhrzeit,
]);

$node->save();

// ... other code 

 

Neuen Kommentar schreiben

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

Suche

Neueste Kommentare