function DrupalDateTime::format
Same name in other branches
- 8.9.x core/lib/Drupal/Core/Datetime/DrupalDateTime.php \Drupal\Core\Datetime\DrupalDateTime::format()
- 10 core/lib/Drupal/Core/Datetime/DrupalDateTime.php \Drupal\Core\Datetime\DrupalDateTime::format()
- 11.x core/lib/Drupal/Core/Datetime/DrupalDateTime.php \Drupal\Core\Datetime\DrupalDateTime::format()
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 121
Class
- DrupalDateTime
- Extends DateTimePlus().
Namespace
Drupal\Core\DatetimeCode
public function format($format, $settings = []) {
$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([
'/\\\\\\\\/',
'/(?<!\\\\)([AaeDlMTF])/',
], [
"\xef\\\\\\\\\xff",
"\xef\\\\\$1\$1\xff",
], $format);
// Call date_format().
$format = parent::format($format, $settings);
// $format will be NULL if there are any errors.
if ($format !== NULL) {
// 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 = [
'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, [], $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;
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.