Skip to main content
Category:

Code snippet that can be used to to get year and month from date_iso8601 for computed field in drupal 8.

Example with date()

$date = $entity->created->value;
$date = date('Y-m-d H:i:s', $date);

 

Example get year

$date = $node->getCreatedTime();
$year = date('Y', $date);

 

Example to get year with date.formatter service:

$date = $node->getCreatedTime();
$year = \Drupal::service('date.formatter')->format($date, 'html_year');

 

Example to get year with DrupalDateTime class:

$date = $node->getCreatedTime();
$date = DrupalDateTime::createFromTimestamp($date);
$year = $date->format('Y');

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook