Formats a date, using a date type or a custom date format string.
int $timestamp: A UNIX timestamp to format.
string $type: (optional) The format to use, one of:
Defaults to 'medium'.
string $format: (optional) If $type is 'custom', a PHP date format string suitable for input to date(). Use a backslash to escape ordinary text, so it does not get interpreted as date format characters.
string $timezone: (optional) Time zone identifier, as described at http://php.net/manual/timezones.php Defaults to the time zone used to display the page.
string $langcode: (optional) Language code to translate to. Defaults to the language used to display the page.
string A translated date string in the requested format.
public function format($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
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);
}
if (empty($langcode)) {
$langcode = $this->languageManager
->getLanguage(Language::TYPE_INTERFACE)->langcode;
}
// Create a DrupalDateTime object from the timestamp and timezone.
$date = new DrupalDateTime($timestamp, $this->timezones[$timezone]);
// Find the appropriate format type.
$key = $date
->canUseIntl() ? DrupalDateTime::INTL : DrupalDateTime::PHP;
// If we have a non-custom date format use the provided date format pattern.
$config = $this->configFactory
->get('system.date');
if ($type != 'custom') {
$format = $config
->get('formats.' . $type . '.pattern.' . $key);
}
// Fall back to medium if a format was not found.
if (empty($format)) {
$format = $config
->get('formats.medium.pattern.' . $key);
}
// Call $date->format().
$settings = array(
'langcode' => $langcode,
'format_string_type' => $key,
);
return Xss::filter($date
->format($format, $settings));
}