You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Timezone.php 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Utilities\Localization;
  3. use App\Enums\TimeFormat;
  4. use App\Models\Setting\Localization;
  5. use DateTimeZone;
  6. use Symfony\Component\Intl\Timezones;
  7. class Timezone
  8. {
  9. public static function getTimezoneOptions(#[\SensitiveParameter] ?string $countryCode = null): array
  10. {
  11. if (empty($countryCode)) {
  12. return [];
  13. }
  14. $countryTimezones = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, strtoupper($countryCode));
  15. if (empty($countryTimezones)) {
  16. return [];
  17. }
  18. $localizedTimezoneNames = Timezones::getNames();
  19. $results = [];
  20. foreach ($countryTimezones as $timezoneIdentifier) {
  21. $translatedName = $localizedTimezoneNames[$timezoneIdentifier] ?? $timezoneIdentifier;
  22. $cityName = self::extractCityName($translatedName);
  23. $localTime = self::getLocalTime($timezoneIdentifier);
  24. $timezoneAbbreviation = now($timezoneIdentifier)->format('T');
  25. $results[$timezoneIdentifier] = "{$cityName} ({$timezoneAbbreviation}) {$localTime}";
  26. }
  27. return $results;
  28. }
  29. public static function extractCityName(string $translatedName): string
  30. {
  31. if (preg_match('/\((.*?)\)/', $translatedName, $match)) {
  32. return trim($match[1]);
  33. }
  34. return $translatedName;
  35. }
  36. public static function getLocalTime(string $timezone): string
  37. {
  38. $localizationModel = Localization::firstOrFail();
  39. $time_format = $localizationModel->time_format->value ?? TimeFormat::DEFAULT;
  40. return now($timezone)->translatedFormat($time_format);
  41. }
  42. }