class DrupalDateTime
Same name in other branches
- 9 core/lib/Drupal/Core/Datetime/DrupalDateTime.php \Drupal\Core\Datetime\DrupalDateTime
- 8.9.x core/lib/Drupal/Core/Datetime/DrupalDateTime.php \Drupal\Core\Datetime\DrupalDateTime
- 11.x core/lib/Drupal/Core/Datetime/DrupalDateTime.php \Drupal\Core\Datetime\DrupalDateTime
Extends DateTimePlus().
This class extends the basic component and adds in Drupal-specific handling, like translation of the format() method.
Static methods in base class can also be used to create DrupalDateTime objects. For example:
DrupalDateTime::createFromArray( array('year' => 2010, 'month' => 9, 'day' => 28) )
Hierarchy
- class \Drupal\Component\Datetime\DateTimePlus uses \Drupal\Component\Utility\ToStringTrait
- class \Drupal\Core\Datetime\DrupalDateTime extends \Drupal\Component\Datetime\DateTimePlus uses \Drupal\Core\StringTranslation\StringTranslationTrait, \Drupal\Core\DependencyInjection\DependencySerializationTrait
Expanded class hierarchy of DrupalDateTime
See also
\Drupal\Component\Datetime\DateTimePlus
38 files declare their use of DrupalDateTime
- Announcement.php in core/
modules/ announcements_feed/ src/ Announcement.php - CommentForm.php in core/
modules/ comment/ src/ CommentForm.php - CommentPreviewTest.php in core/
modules/ comment/ tests/ src/ Functional/ CommentPreviewTest.php - DateElementBase.php in core/
lib/ Drupal/ Core/ Datetime/ Element/ DateElementBase.php - Datelist.php in core/
lib/ Drupal/ Core/ Datetime/ Element/ Datelist.php
File
-
core/
lib/ Drupal/ Core/ Datetime/ DrupalDateTime.php, line 22
Namespace
Drupal\Core\DatetimeView source
class DrupalDateTime extends DateTimePlus {
use StringTranslationTrait;
use DependencySerializationTrait {
__sleep as defaultSleep;
}
/**
* Formatted strings translation cache.
*
* Translation cache represents an instance storage for formatted date
* strings. It contains a multidimensional array where:
* - first level keys - are drupal language codes;
* - second level keys - are each symbols of given format string (like 'F');
* - third level keys - are original matched strings related to the symbol;
* - values - are translated or not-translated original strings (depends on
* if a particular symbol represents translatable value according to PHP's
* date() format character).
*
* For example:
* @code
* [
* 'en' => [
* 'F' => [
* 'November' => t('November'),
* 'December' => t('December'),
* ],
* 'd' => [
* '10' => '10',
* '31' => '31',
* ],
* ],
* ]
* @endcode
*
* @var array
*/
protected $formatTranslationCache = [];
/**
* Constructs a date object.
*
* @param string $time
* A date/input_time_adjusted string. Defaults to 'now'.
* @param mixed $timezone
* PHP DateTimeZone object, string or NULL allowed.
* Defaults to NULL. Note that the $timezone parameter and the current
* timezone are ignored when the $time parameter either is a UNIX timestamp
* (e.g. @946684800) or specifies a timezone
* (e.g. 2010-01-28T15:00:00+02:00).
* @see http://php.net/manual/datetime.construct.php
* @param array $settings
* - validate_format: (optional) Boolean choice to validate the
* created date using the input format. The format used in
* createFromFormat() allows slightly different values than format().
* Using an input format that works in both functions makes it
* possible to a validation step to confirm that the date created
* from a format string exactly matches the input. This option
* indicates the format can be used for validation. Defaults to TRUE.
* - langcode: (optional) Used to control the result of the format() method.
* Defaults to NULL.
* - debug: (optional) Boolean choice to leave debug values in the
* date object for debugging purposes. Defaults to FALSE.
*/
public function __construct($time = 'now', $timezone = NULL, $settings = []) {
if (!isset($settings['langcode'])) {
$settings['langcode'] = \Drupal::languageManager()->getCurrentLanguage()
->getId();
}
// Instantiate the parent class.
parent::__construct($time, $timezone, $settings);
}
/**
* Overrides prepareTimezone().
*
* Override basic component timezone handling to use Drupal's
* knowledge of the preferred user timezone.
*/
protected function prepareTimezone($timezone) {
if (empty($timezone)) {
// Fallback to user or system default timezone.
$timezone = date_default_timezone_get();
}
return parent::prepareTimezone($timezone);
}
/**
* Overrides format().
*
* @param string $format
* A format string using either PHP's date().
* @param 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 string
* The formatted value of the date. Since the format may contain user input,
* this value should be escaped when output.
*/
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;
}
/**
* {@inheritdoc}
*/
public function __sleep() : array {
return array_diff($this->defaultSleep(), [
'formatTranslationCache',
]);
}
}
Members
Title Sort descending | Modifiers | Object type | Summary | Member alias | Overriden Title | Overrides |
---|---|---|---|---|---|---|
DateTimePlus::$dateParts | protected static | property | An array of possible date parts. | |||
DateTimePlus::$dateTimeObject | protected | property | The DateTime object. | |||
DateTimePlus::$errors | protected | property | An array of errors encountered when creating this date. | |||
DateTimePlus::$inputFormatAdjusted | protected | property | The prepared format, if provided. | |||
DateTimePlus::$inputFormatRaw | protected | property | The value of the format passed to the constructor. | |||
DateTimePlus::$inputTimeAdjusted | protected | property | The prepared time, without timezone, for this date. | |||
DateTimePlus::$inputTimeRaw | protected | property | The value of the time value passed to the constructor. | |||
DateTimePlus::$inputTimeZoneAdjusted | protected | property | The prepared timezone object used to construct this date. | |||
DateTimePlus::$inputTimeZoneRaw | protected | property | The value of the timezone passed to the constructor. | |||
DateTimePlus::$langcode | protected | property | The value of the language code passed to the constructor. | |||
DateTimePlus::arrayToISO | public static | function | Creates an ISO date from an array of values. | |||
DateTimePlus::checkArray | public static | function | Checks that arrays of date parts will create a valid date. | |||
DateTimePlus::checkErrors | public | function | Examines getLastErrors() to see what errors to report. | |||
DateTimePlus::createFromArray | public static | function | Creates a date object from an array of date parts. | |||
DateTimePlus::createFromDateTime | public static | function | Creates a date object from an input date object. | |||
DateTimePlus::createFromFormat | public static | function | Creates a date object from an input format. | |||
DateTimePlus::createFromTimestamp | public static | function | Creates a date object from timestamp input. | |||
DateTimePlus::datePad | public static | function | Pads date parts with zeros. | |||
DateTimePlus::diff | public | function | Returns the difference between two DateTimePlus objects. | |||
DateTimePlus::FORMAT | constant | 1 | ||||
DateTimePlus::getErrors | public | function | Gets error messages. | |||
DateTimePlus::getPhpDateTime | public | function | Gets a clone of the proxied PHP \DateTime object wrapped by this class. | |||
DateTimePlus::hasErrors | public | function | Detects if there were errors in the processing of this date. | |||
DateTimePlus::prepareArray | public static | function | Creates a complete array from a possibly incomplete array of date parts. | |||
DateTimePlus::prepareFormat | protected | function | Prepares the input format value. | |||
DateTimePlus::prepareTime | protected | function | Prepares the input time value. | |||
DateTimePlus::render | public | function | Renders the timezone name. | Overrides ToStringTrait::render | ||
DateTimePlus::RFC7231 | constant | A RFC7231 Compliant date. | ||||
DateTimePlus::setDefaultDateTime | public | function | Sets the default time for an object built from date-only data. | |||
DateTimePlus::__call | public | function | Implements the magic __call method. | |||
DateTimePlus::__callStatic | public static | function | Implements the magic __callStatic method. | |||
DateTimePlus::__clone | public | function | Implements the magic __clone method. | |||
DependencySerializationTrait::$_entityStorages | protected | property | ||||
DependencySerializationTrait::$_serviceIds | protected | property | ||||
DependencySerializationTrait::__sleep | public | function | Aliased as: defaultSleep | 1 | ||
DependencySerializationTrait::__wakeup | public | function | 2 | |||
DrupalDateTime::$formatTranslationCache | protected | property | Formatted strings translation cache. | |||
DrupalDateTime::format | public | function | Overrides format(). | Overrides DateTimePlus::format | ||
DrupalDateTime::prepareTimezone | protected | function | Overrides prepareTimezone(). | Overrides DateTimePlus::prepareTimezone | ||
DrupalDateTime::__construct | public | function | Constructs a date object. | Overrides DateTimePlus::__construct | ||
DrupalDateTime::__sleep | public | function | ||||
StringTranslationTrait::$stringTranslation | protected | property | The string translation service. | 3 | ||
StringTranslationTrait::formatPlural | protected | function | Formats a string containing a count of items. | |||
StringTranslationTrait::getNumberOfPlurals | protected | function | Returns the number of plurals supported by a given language. | |||
StringTranslationTrait::getStringTranslation | protected | function | Gets the string translation service. | |||
StringTranslationTrait::setStringTranslation | public | function | Sets the string translation service to use. | 2 | ||
StringTranslationTrait::t | protected | function | Translates a string to the current language or to a given language. | |||
ToStringTrait::_die | protected | function | For test purposes, wrap die() in an overridable method. | |||
ToStringTrait::__toString | public | function | Implements the magic __toString() method. |
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.