I try to use the DrupalDateTime
class in my theme to show native date and time in custom format based on special TimeZone in my nodes.
According to New Datetime API DrupalDateTime
should be used instead of the PHP DateTime
class or to functions like date()
, gmdate()
, or strtotime()
.
I am using the following code in a theme.
function MyThemeName_preprocess_node(&$variables){
$node_date = $variables['node']->getCreatedTime();
$date = new DrupalDateTime($node_date, 'UTC');
$date->setTimezone(new \DateTimeZone('Asia/Tehran'));
$variables['date'] = $date->format('Y/m/d');
}
I get this error
Exception: DateTime object not set. in Drupal\Component\Datetime\DateTimePlus->__call() (line 308 of core\lib\Drupal\Component\Datetime\DateTimePlus.php).