You are here

CalendarSystemsDateFormatter.php in Calendar Systems 8.2

File

src/Services/DateFormatter/CalendarSystemsDateFormatter.php
View source
<?php

namespace Drupal\calendar_systems\Services\DateFormatter;

use Drupal\Core\Datetime\DateFormatter;
use Drupal\calendar_systems\Helpers;
class CalendarSystemsDateFormatter extends DateFormatter {
  public function format($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {

    // Return default formatter needs caller needs machine-readable data
    $calendar_name = Helpers::calendar_systems_get_calendar_system_name();
    $calendar = Helpers::calendar_systems_get_calendar_instance();
    if ($calendar_name == 'default' || !$calendar || Helpers::shouldIgnoreCalendarSystemsDateConversion()) {
      return parent::format($timestamp, $type, $format, $timezone, $langcode);
    }
    if (!isset($timezone)) {
      $timezone = date_default_timezone_get();
    }

    // Store DateTimeZone objects in an array rather than repeatedly
    // constructing identical objects over the life of a request.
    if (!isset($this->timezones[$timezone])) {
      $this->timezones[$timezone] = timezone_open($timezone);
    }
    $calendar
      ->setTimeZoneOffset($this->timezones[$timezone]
      ->getOffset());

    //$cal->setTimestamp($timestamp);
    if (empty($langcode)) {
      $langcode = $this->languageManager
        ->getCurrentLanguage()
        ->getId();
    }

    // If we have a non-custom date format use the provided date format pattern.
    if ($type !== 'custom') {
      if ($date_format = $this
        ->dateFormat($type, $langcode)) {
        $format = $date_format
          ->getPattern();
      }
    }

    // Fall back to the 'medium' date format type if the format string is
    // empty, either from not finding a requested date format or being given an
    // empty custom format string.
    if (empty($format)) {
      $format = $this
        ->dateFormat('fallback', $langcode)
        ->getPattern();
    }
    return $calendar
      ->timestampToStr($format, $timestamp + $this->timezones[$timezone]
      ->getOffset());
  }

}

Classes