public function DrupalDateTime::format

public DrupalDateTime::format($format, $settings = array())

Overrides format().

Parameters

string $format: A format string using either PHP's date().

array $settings:

  • timezone: (optional) String timezone name. Defaults to the timezone of the date object.
  • langcode: (optional) String two letter language code used to control the result of the format() method. Defaults to NULL.

Return value

string The formatted value of the date. Since the format may contain user input, this value should be escaped when output.

Overrides DateTimePlus::format

File

core/lib/Drupal/Core/Datetime/DrupalDateTime.php, line 90

Class

DrupalDateTime
Extends DateTimePlus().

Namespace

Drupal\Core\Datetime

Code

public function format($format, $settings = array()) {
  $langcode = !empty($settings['langcode']) ? $settings['langcode'] : $this->langcode;
  $value = '';
  // Format the date and catch errors.
  try {
    // Encode markers that should be translated. 'A' becomes
    // '\xEF\AA\xFF'. xEF and xFF are invalid UTF-8 sequences,
    // and we assume they are not in the input string.
    // Paired backslashes are isolated to prevent errors in
    // read-ahead evaluation. The read-ahead expression ensures that
    // A matches, but not \A.
    $format = preg_replace(array('/\\\\\\\\/', '/(?<!\\\\)([AaeDlMTF])/'), array("\xEF\\\\\\\\\xFF", "\xEF\\\\\$1\$1\xFF"), $format);

    // Call date_format().
    $format = parent::format($format, $settings);

    // Translates a formatted date string.
    $translation_callback = function($matches) use ($langcode) {
      $code = $matches[1];
      $string = $matches[2];
      if (!isset($this->formatTranslationCache[$langcode][$code][$string])) {
        $options = array('langcode' => $langcode);
        if ($code == 'F') {
          $options['context'] = 'Long month name';
        }

        if ($code == '') {
          $this->formatTranslationCache[$langcode][$code][$string] = $string;
        }
        else {
          $this->formatTranslationCache[$langcode][$code][$string] = $this->t($string, array(), $options);
        }
      }
      return $this->formatTranslationCache[$langcode][$code][$string];
    };

    // Translate the marked sequences.
    $value = preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', $translation_callback, $format);
  }
  catch (\Exception $e) {
    $this->errors[] = $e->getMessage();
  }
  return $value;
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Datetime!DrupalDateTime.php/function/DrupalDateTime::format/8.1.x