Skip to main content
2 of 2
added 832 characters in body
avpaderno
  • 97.9k
  • 15
  • 164
  • 284

The code you are showing is wrong because DrupalDateTime::__construct() is expecting a string, while you are passing an integer, which is what Node::getCreatedTime() returns.

Instead of DrupalDateTime::__construct(), you should use DrupalDateTime::createFromTimestamp().

$date = DrupalDateTime::createFromTimestamp($variables['node']->getCreatedTime(), 'UTC');

Since the static method also accept a \DateTimeZone object as second parameter, your code could be similar to the following one.

if (isset($variables['node'])) {
  $date = DrupalDateTime::createFromTimestamp($variables['node']->getCreatedTime(), new \DateTimeZone('Asia/Tehran'));
  $variables['date'] = $date->format('Y/m/d');
}

Since you seem interested to get strings in a specific language, you should also set the language code.

if (isset($variables['node'])) {
  $date = DrupalDateTime::createFromTimestamp($variables['node']->getCreatedTime(), new \DateTimeZone('Asia/Tehran'), ['langcode' => 'the language code for the language you need']);
  $variables['date'] = $date->format('Y/m/d');
}
avpaderno
  • 97.9k
  • 15
  • 164
  • 284