Elgg  Version 6.1
DateTime.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\I18n;
4 
5 use DateTime as PHPDateTime;
6 
12 class DateTime extends PHPDateTime {
13 
22  public function formatLocale(string $format, string $language = null) {
23  if (!isset($language)) {
24  $language = _elgg_services()->translator->getCurrentLanguage();
25  }
26 
27  $result = $this->formatIntl($format, $language);
28 
29  if ($result === false) {
30  _elgg_services()->logger->info("Unable to generate locale representation for format: '{$format}', using non-locale version");
31  return $this->format($format);
32  }
33 
34  return $result;
35  }
36 
46  protected function dateFormatToICU(string $dateFormat) {
47  if (preg_match('/(?<!\\|%)[BcILrtuUVZ]/', $dateFormat)) {
48  // unsupported characters found
49  return false;
50  }
51 
52  $caracs = [
53  // Day
54  'd' => 'dd', 'D' => 'EEE', 'j' => 'd', 'l' => 'EEEE', 'N' => 'e', 'w' => 'c', 'z' => 'D',
55  // Week
56  'W' => 'w',
57  // Month
58  'F' => 'MMMM', 'm' => 'MM', 'M' => 'MMM', 'n' => 'M',
59  // Year
60  'o' => 'Y', 'Y' => 'yyyy', 'y' => 'yy',
61  // Time
62  'a' => 'a', 'A' => 'a', 'g' => 'h', 'G' => 'H', 'h' => 'hh', 'H' => 'HH', 'i' => 'mm', 's' => 'ss',
63  // Timezone
64  'e' => 'VV', 'O' => 'xx', 'P' => 'xxx', 'p' => 'XXX', 'T' => 'zzz',
65  // less supported replacements
66  // Day
67  'S' => '',
68  ];
69 
70  return strtr((string) $dateFormat, $caracs);
71  }
72 
82  protected function formatIntl(string $format, string $language) {
83  $correct_format = $this->dateFormatToICU($format);
84  if ($correct_format === false) {
85  return false;
86  }
87 
88  $locale_for_language = _elgg_services()->locale->getLocaleForLanguage($language);
89 
90  try {
91  $locale = new \IntlDateFormatter(elgg_extract(0, $locale_for_language, $language), \IntlDateFormatter::FULL, \IntlDateFormatter::FULL);
92  $locale->setPattern($correct_format);
93 
94  return $locale->format($this);
95  } catch (\Throwable $t) {
96  // something went wrong
97  // @see https://github.com/Elgg/Elgg/issues/14712
98  }
99 
100  return false;
101  }
102 }
$format
Definition: date.php:37
formatIntl(string $format, string $language)
Try to format to a locale using the &#39;intl&#39; PHP module.
Definition: DateTime.php:82
dateFormatToICU(string $dateFormat)
Convert a date format to a ICU format.
Definition: DateTime.php:46
elgg_extract($key, $array, $default=null, bool $strict=true)
Checks for $array[$key] and returns its value if it exists, else returns $default.
Definition: elgglib.php:256
$language
Definition: useradd.php:17
formatLocale(string $format, string $language=null)
Try to format the date using locale output.
Definition: DateTime.php:22
Extension of the DateTime class to support formatting a date using the locale.
Definition: DateTime.php:12
_elgg_services()
Get the global service provider.
Definition: elgglib.php:353