Elgg  Version 3.0
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 
26  protected function dateFormatToStrftime(string $dateFormat) {
27 
28  if (preg_match('/(?<!\\|%)[ntLBueIPZcr]/', $dateFormat)) {
29  // unsupported characters found
30  return false;
31  }
32 
33  $caracs = [
34  // Day - no strf eq : S
35  'd' => '%d', 'D' => '%a', 'j' => '%e', 'l' => '%A', 'N' => '%u', 'w' => '%w', 'z' => '%j',
36  // Week - no date eq : %U, %W
37  'W' => '%V',
38  // Month - no strf eq : n, t
39  'F' => '%B', 'm' => '%m', 'M' => '%b',
40  // Year - no strf eq : L; no date eq : %C, %g
41  'o' => '%G', 'Y' => '%Y', 'y' => '%y',
42  // Time - no strf eq : B, G, u; no date eq : %r, %R, %T, %X
43  'a' => '%P', 'A' => '%p', 'g' => '%l', 'h' => '%I', 'H' => '%H', 'i' => '%M', 's' => '%S',
44  // Timezone - no strf eq : e, I, P, Z
45  'O' => '%z', 'T' => '%Z',
46  // Full Date / Time - no strf eq : c, r; no date eq : %c, %D, %F, %x
47  'U' => '%s',
48  // less supported replacements
49  // Day
50  'S' => '',
51  // Time
52  'G' => '%k',
53  ];
54 
55  return strtr((string) $dateFormat, $caracs);
56  }
57 
66  public function formatLocale(string $format, string $language = null) {
67  // convert date() format to strftime() format
68  $correct_format = $this->dateFormatToStrftime($format);
69  if ($correct_format === false) {
70  elgg_log("Unable to convert date format: '{$format}', using non-locale version", 'INFO');
71  return $this->format($format);
72  }
73 
74  // switch locale
75  $current_locale = elgg()->locale->setLocaleFromLanguageKey(LC_TIME, $language);
76 
77  $result = strftime($correct_format, $this->getTimestamp());
78 
79  // restore locale
80  elgg()->locale->setLocale(LC_TIME, $current_locale);
81 
82  if ($result === false) {
83  elgg_log("Unable to generate locale representation for format: '{$correct_format}', using non-locale version", 'INFO');
84  return $this->format($format);
85  }
86 
87  return $result;
88  }
89 }
$format
Definition: date.php:36
$language
Definition: useradd.php:17
formatLocale(string $format, string $language=null)
Format the date using strftime() which supports locale output.
Definition: DateTime.php:66
elgg_log($message, $level=\Psr\Log\LogLevel::NOTICE)
Log a message.
Definition: elgglib.php:786
dateFormatToStrftime(string $dateFormat)
Convert a date format to a strftime format.
Definition: DateTime.php:26
var elgg
Definition: elgglib.js:4