Drupal 8.4x: Add Timezone to Date or DateRange Field


Here's the controlling issue for adding timezone support to Drupal core. As of now, August 1st, 2017, it doesn't appear to be ready.

Instead, I just added a timezone field to the node using the Timezone module, then appended it to the date range on field preprocess.

This won't work for you if you have multiple dates on an entity with different timezones (you might want to try the patch linked above), but it will fit most use cases.

function mytheme_preprocess_field(&$variables, $hook) {
  if ($variables['field_name'] == 'my_date_field') {
    if (isset($variables['items'][0]['content']['end_date']['#plain_text'])) {
      $node =& $variables['element']['#object'];
      $timezone = $node->get('my_timezone_field')->getString() ? $node->get('my_timezone_field')->getString() : drupal_get_user_timezone();
      $dateTime = new DateTime();
      $dateTime->setTimeZone(new DateTimeZone($timezone));
      $variables['items'][0]['content']['end_date']['#plain_text'] .= ' ' . $dateTime->format('T'); // Outputs the abbreviated timezone appended to to the date range.

About the Author

Hi. My name is Jeremiah John. I'm a sf/f writer and activist.

I just completed a dystopian science fiction novel. I run a website which I created that connects farms with churches, mosques, and synagogues to buy fresh vegetables directly and distribute them on a sliding scale to those in need.

In 2003, I spent six months in prison for civil disobedience while working to close the School of the Americas, converting to Christianity, as one does, while I was in the clink.