Example #1
1
 public static function all()
 {
     $timeZones = [];
     $timeZonesOutput = [];
     $now = new \DateTime('now', new \DateTimeZone('UTC'));
     foreach (\DateTimeZone::listIdentifiers(\DateTimeZone::ALL) as $timeZone) {
         $now->setTimezone(new \DateTimeZone($timeZone));
         $timeZones[] = [$now->format('P'), $timeZone];
     }
     if (self::$sortBy == static::SORT_OFFSET) {
         array_multisort($timeZones);
     }
     foreach ($timeZones as $timeZone) {
         $content = preg_replace_callback("/{\\w+}/", function ($matches) use($timeZone) {
             switch ($matches[0]) {
                 case '{name}':
                     return $timeZone[1];
                 case '{offset}':
                     return $timeZone[0];
                 default:
                     return $matches[0];
             }
         }, self::$template);
         $timeZonesOutput[$timeZone[1]] = $content;
     }
     return $timeZonesOutput;
 }
Example #2
0
 /**
  * @return $this
  * @throws Exception
  */
 public function beforeSave()
 {
     if (!in_array($this->getValue(), \DateTimeZone::listIdentifiers(\DateTimeZone::ALL_WITH_BC))) {
         throw new Exception(__('Please correct the timezone.'));
     }
     return $this;
 }
Example #3
0
function timezones()
{
    $list = DateTimeZone::listIdentifiers();
    $data = array();
    foreach ($list as $id => $zone) {
        $now = new DateTime(null, new DateTimeZone($zone));
        $offset = $now->getOffset();
        $offset_round = round(abs($offset / 3600), 2);
        $minutes = fmod($offset_round, 1);
        if ($minutes == 0) {
            $offset_label = $offset_round . '  ';
        } elseif ($minutes == 0.5) {
            $offset_label = (int) $offset_round . '.30';
        } elseif ($minutes == 0.75) {
            $offset_label = (int) $offset_round . '.45';
        }
        $sign = $offset > 0 ? '+' : '-';
        if ($offset == 0) {
            $sign = ' ';
            $offset = '';
        }
        $label = 'GMT' . $sign . $offset_label . ' ' . $zone;
        $data[$offset][$zone] = array('offset' => $offset, 'label' => $label, 'timezone_id' => $zone);
    }
    ksort($data);
    $timezones = array();
    foreach ($data as $offsets) {
        ksort($offsets);
        foreach ($offsets as $zone) {
            $timezones[] = $zone;
        }
    }
    return $timezones;
}
Example #4
0
function getSystemTimeZoneMenu()
{
    $currentTZ = getCurrentTimeZone();
    echo "<select id=\"timezone\" name=\"timezone\">\n";
    $timezone_identifiers = DateTimeZone::listIdentifiers();
    foreach ($timezone_identifiers as $value) {
        if (preg_match('/^(America|Australia|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\\//', $value)) {
            if (!isset($continent)) {
                $continent = '';
            }
            $ex = explode("/", $value);
            //obtain continent,city
            if ($continent != $ex[0]) {
                if ($continent != "") {
                    $return = '</optgroup>' . "\n";
                }
                echo '<optgroup label="' . $ex[0] . '">' . "\n";
            }
            $city = $ex[1];
            $continent = $ex[0];
            echo '<option value="' . $value . '"' . ($value == $currentTZ ? " selected=\"selected\"" : "") . '>' . $city . (isset($ex[2]) ? "/" . $ex[2] : "") . '</option>' . "\n";
        }
    }
    echo "</optgroup>\n";
    echo "</select>\n";
}
 /**
  * {@inheritdoc}
  */
 public function up()
 {
     // only run this task if there aren't any time zones defined yet
     if (TimeZoneData::get()->count() == 0) {
         $this->message('Adding new time zone entries.');
         // prepare the information provided by PHP
         $timezones = DateTimeZone::listIdentifiers();
         foreach ($timezones as $timezone) {
             // replace some strings to increase the readibility.
             $tzNice = str_replace(array_keys($this->replacementMap), array_values($this->replacementMap), $timezone);
             // split the time zone information into the sections
             $timezoneParts = explode('/', $tzNice);
             // adding the new time zone
             $tz = new TimeZoneData();
             $tz->Identifier = $timezone;
             $tz->Region = $timezoneParts[0];
             $tz->Name = array_pop($timezoneParts);
             $tz->write();
         }
         $this->message('Finished adding new time zone entries.');
     }
     // check if the titles in the dataobjects need to be refreshed
     if ($this->checkIfTitlesNeedRebuild()) {
         $this->rebuildTitles();
     }
 }
 public function validateValue($value)
 {
     $list = \DateTimeZone::listIdentifiers();
     if (!in_array($value, $list)) {
         return ['Invalid timezone value', []];
     }
 }
Example #7
0
 /**
  * Method to get a list of options for a list input.
  *
  * @return	array		An array of JHtml options.
  */
 protected function _getGroups()
 {
     if (strlen($this->value) == 0) {
         $conf =& JFactory::getConfig();
         $value = $conf->getValue('config.offset');
     }
     $zones = DateTimeZone::listIdentifiers();
     foreach ($zones as $zone) {
         // 0 => Continent, 1 => City
         $zone = explode('/', $zone);
         // Only use "friendly" continent names
         if ($zone[0] == 'Africa' || $zone[0] == 'America' || $zone[0] == 'Antarctica' || $zone[0] == 'Arctic' || $zone[0] == 'Asia' || $zone[0] == 'Atlantic' || $zone[0] == 'Australia' || $zone[0] == 'Europe' || $zone[0] == 'Indian' || $zone[0] == 'Pacific') {
             if (isset($zone[1]) != '') {
                 // Creates array(DateTimeZone => 'Friendly name')
                 $groups[$zone[0]][$zone[0] . '/' . $zone[1]] = str_replace('_', ' ', $zone[1]);
             }
         }
     }
     // Sort the arrays
     ksort($groups);
     foreach ($groups as $zone => $location) {
         sort($location);
     }
     // Merge any additional options in the XML definition.
     $groups = array_merge(parent::_getGroups(), $groups);
     return $groups;
 }
 /**
  * Initialize the Sele
  */
 public function init()
 {
     $this->setLabel('general settings');
     $this->add(array('type' => 'Zend\\Form\\Element\\Select', 'name' => 'language', 'options' => array('label' => 'choose your language', 'value_options' => array('en' => 'English', 'fr' => 'French', 'de' => 'German', 'it' => 'Italian', 'po' => 'Polish', 'ru' => 'Russian', 'tr' => 'Turkish', 'es' => 'Spanish'), 'description' => 'defines the languages of this frontend.')));
     $timezones = array_merge(\DateTimeZone::listIdentifiers(\DateTimeZone::AFRICA), \DateTimeZone::listIdentifiers(\DateTimeZone::AMERICA), \DateTimeZone::listIdentifiers(\DateTimeZone::ASIA), \DateTimeZone::listIdentifiers(\DateTimeZone::ATLANTIC), \DateTimeZone::listIdentifiers(\DateTimeZone::AUSTRALIA), \DateTimeZone::listIdentifiers(\DateTimeZone::EUROPE), \DateTimeZone::listIdentifiers(\DateTimeZone::INDIAN), \DateTimeZone::listIdentifiers(\DateTimeZone::PACIFIC));
     $this->add(array('type' => 'Zend\\Form\\Element\\Select', 'name' => 'timezone', 'options' => array('label' => 'choose your timzone', 'value_options' => $timezones, 'description' => 'defines your local timezone.')));
 }
Example #9
0
    /**
     * Loads the timezone choices
     *
     * The choices are generated from the ICU function
     * \DateTimeZone::listIdentifiers(). They are cached during a single request,
     * so multiple timezone fields on the same page don't lead to unnecessary
     * overhead.
     *
     * @return array  The timezone choices
     */
    protected function load()
    {
        parent::load();

        if (count(self::$timezones) == 0) {
            foreach (\DateTimeZone::listIdentifiers() as $timezone) {
                $parts = explode('/', $timezone);

                if (count($parts) > 2) {
                    $region = $parts[0];
                    $name = $parts[1].' - '.$parts[2];
                } else if (count($parts) > 1) {
                    $region = $parts[0];
                    $name = $parts[1];
                } else {
                    $region = 'Other';
                    $name = $parts[0];
                }

                if (!isset(self::$timezones[$region])) {
                    self::$timezones[$region] = array();
                }

                self::$timezones[$region][$timezone] = str_replace('_', ' ', $name);
            }
        }

        $this->choices = self::$timezones;
    }
function timezones_from_countryCode($country_code, $country_name)
{
    $dt = new DateTime();
    // create a list of timezones based on that country code..
    $timezones = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $country_code);
    $timezone_offset = [];
    // instantiate timezone_offset array
    foreach ($timezones as $timezone) {
        $tz = new DateTimeZone($timezone);
        $timezone_offset[$timezone] = $tz->getOffset(new DateTime());
    }
    // sort by offset
    asort($timezone_offset);
    // format display of timezone and offset
    foreach ($timezone_offset as $raw_timezone => $offset) {
        $dt->setTimezone(new DateTimeZone($raw_timezone));
        $timezone_abbr = $dt->format('T');
        $offset_prefix = $offset < 0 ? '-' : '+';
        $offset_formatted = gmdate('H:i', abs($offset));
        $pretty_offset = "UTC{$offset_prefix}{$offset_formatted}";
        // if( ($pos = strpos($raw_timezone, '/') ) !== false ) { // remove 'America/'
        // 	$clean_timezone = substr($raw_timezone, $pos+1);
        // 	if( ($pos = strpos($clean_timezone, '/')) !== false ) { // remove second level '.../'
        // 		$clean_timezone = substr($clean_timezone, $pos+1);
        // 	}
        // }
        // $clean_timezone = str_replace('_',' ',$clean_timezone); // remove the '_' in city names
        $clean_timezone = User::clean_city($raw_timezone);
        echo "<option value=\"{$raw_timezone}\">(" . $pretty_offset . ") " . $clean_timezone . ' (' . $timezone_abbr . ')</option>';
    }
}
Example #11
0
 /**
  * Guess the DateTimeZone for a given offset
  *
  * We first try to find a Etc/GMT* timezone, if that does not exist,
  * we try to find it manually, before falling back to UTC.
  *
  * @param mixed $offset
  * @param bool|int $timestamp
  * @return \DateTimeZone
  */
 protected function guessTimeZoneFromOffset($offset, $timestamp)
 {
     try {
         // Note: the timeZone name is the inverse to the offset,
         // so a positive offset means negative timeZone
         // and the other way around.
         if ($offset > 0) {
             $timeZone = 'Etc/GMT-' . $offset;
         } else {
             $timeZone = 'Etc/GMT+' . abs($offset);
         }
         return new \DateTimeZone($timeZone);
     } catch (\Exception $e) {
         // If the offset has no Etc/GMT* timezone,
         // we try to guess one timezone that has the same offset
         foreach (\DateTimeZone::listIdentifiers() as $timeZone) {
             $dtz = new \DateTimeZone($timeZone);
             $dateTime = new \DateTime();
             if ($timestamp !== false) {
                 $dateTime->setTimestamp($timestamp);
             }
             $dtOffset = $dtz->getOffset($dateTime);
             if ($dtOffset == 3600 * $offset) {
                 return $dtz;
             }
         }
         // No timezone found, fallback to UTC
         \OCP\Util::writeLog('datetimezone', 'Failed to find DateTimeZone for offset "' . $offset . "'", \OCP\Util::DEBUG);
         return new \DateTimeZone($this->getDefaultTimeZone());
     }
 }
 public function processRequest(AphrontRequest $request)
 {
     $user = $request->getUser();
     $username = $user->getUsername();
     $pref_time = PhabricatorUserPreferences::PREFERENCE_TIME_FORMAT;
     $pref_date = PhabricatorUserPreferences::PREFERENCE_DATE_FORMAT;
     $pref_week_start = PhabricatorUserPreferences::PREFERENCE_WEEK_START_DAY;
     $preferences = $user->loadPreferences();
     $errors = array();
     if ($request->isFormPost()) {
         $new_timezone = $request->getStr('timezone');
         if (in_array($new_timezone, DateTimeZone::listIdentifiers(), true)) {
             $user->setTimezoneIdentifier($new_timezone);
         } else {
             $errors[] = pht('The selected timezone is not a valid timezone.');
         }
         $preferences->setPreference($pref_time, $request->getStr($pref_time))->setPreference($pref_date, $request->getStr($pref_date))->setPreference($pref_week_start, $request->getStr($pref_week_start));
         if (!$errors) {
             $preferences->save();
             $user->save();
             return id(new AphrontRedirectResponse())->setURI($this->getPanelURI('?saved=true'));
         }
     }
     $timezone_ids = DateTimeZone::listIdentifiers();
     $timezone_id_map = array_fuse($timezone_ids);
     $form = new AphrontFormView();
     $form->setUser($user)->appendChild(id(new AphrontFormSelectControl())->setLabel(pht('Timezone'))->setName('timezone')->setOptions($timezone_id_map)->setValue($user->getTimezoneIdentifier()))->appendChild(id(new AphrontFormSelectControl())->setLabel(pht('Time-of-Day Format'))->setName($pref_time)->setOptions(array('g:i A' => pht('12-hour (2:34 PM)'), 'H:i' => pht('24-hour (14:34)')))->setCaption(pht('Format used when rendering a time of day.'))->setValue($preferences->getPreference($pref_time)))->appendChild(id(new AphrontFormSelectControl())->setLabel(pht('Date Format'))->setName($pref_date)->setOptions(array('Y-m-d' => pht('ISO 8601 (2000-02-28)'), 'n/j/Y' => pht('US (2/28/2000)'), 'd-m-Y' => pht('European (28-02-2000)')))->setCaption(pht('Format used when rendering a date.'))->setValue($preferences->getPreference($pref_date)))->appendChild(id(new AphrontFormSelectControl())->setLabel(pht('Week Starts On'))->setOptions($this->getWeekDays())->setName($pref_week_start)->setCaption(pht('Calendar weeks will start with this day.'))->setValue($preferences->getPreference($pref_week_start, 0)))->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Save Account Settings')));
     $form_box = id(new PHUIObjectBoxView())->setHeaderText(pht('Date and Time Settings'))->setFormSaved($request->getStr('saved'))->setFormErrors($errors)->setForm($form);
     return array($form_box);
 }
 /**
  * returns eshop timezone
  * @return DateTimeZone|null
  */
 private function getEshopTimezone()
 {
     if (version_compare(VERSION, '2.0.1.0', '>=')) {
         $keyName = 'code';
     } elseif (version_compare(VERSION, '1.5', '>=')) {
         $keyName = 'group';
     }
     $result = $this->connection->query("SELECT " . "  `z`.`code` as code " . " FROM  {$this->getTableName('setting')} as s " . " INNER JOIN {$this->getTableName('zone')} as z " . " ON `s`.`value` = `z`.`zone_id` " . " WHERE `s`.`{$keyName}` = 'config' " . " AND " . " `s`.`key` = 'config_zone_id'; ")->fetchAll();
     if (count($result) == 0 || !isset($result[0]) || !isset($result[0][$keyName])) {
         return null;
     }
     $code = $result[0][$keyName];
     $relativeTimezones = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $code);
     if (!$relativeTimezones || empty($relativeTimezones)) {
         return null;
     }
     $relativeTimezone = null;
     foreach ($relativeTimezones as $timezone) {
         $relativeTimezone = $timezone;
         break;
     }
     if ($relativeTimezone === null) {
         return null;
     }
     return new DateTimeZone($relativeTimezone);
 }
 public static function get_nearest_timezone($cur_lat, $cur_long, $country_code = '')
 {
     $timezone_ids = $country_code ? DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $country_code) : DateTimeZone::listIdentifiers();
     if ($timezone_ids && is_array($timezone_ids) && isset($timezone_ids[0])) {
         $time_zone = '';
         $tz_distance = 0;
         //only one identifier?
         if (count($timezone_ids) == 1) {
             $time_zone = $timezone_ids[0];
         } else {
             foreach ($timezone_ids as $timezone_id) {
                 $timezone = new DateTimeZone($timezone_id);
                 $location = $timezone->getLocation();
                 $tz_lat = $location['latitude'];
                 $tz_long = $location['longitude'];
                 $theta = $cur_long - $tz_long;
                 $distance = sin(deg2rad($cur_lat)) * sin(deg2rad($tz_lat)) + cos(deg2rad($cur_lat)) * cos(deg2rad($tz_lat)) * cos(deg2rad($theta));
                 $distance = acos($distance);
                 $distance = abs(rad2deg($distance));
                 // echo '<br />'.$timezone_id.' '.$distance;
                 if (!$time_zone || $tz_distance > $distance) {
                     $time_zone = $timezone_id;
                     $tz_distance = $distance;
                 }
             }
         }
         return $time_zone;
     }
     return 'unknown';
 }
 function ReadData($targetstring, &$map, &$item)
 {
     $data[IN] = NULL;
     $data[OUT] = NULL;
     $data_time = 0;
     $itemname = $item->name;
     $matches = 0;
     if (preg_match("/^time:(.*)\$/", $targetstring, $matches)) {
         $timezone = $matches[1];
         $timezone_l = strtolower($timezone);
         $timezone_identifiers = DateTimeZone::listIdentifiers();
         foreach ($timezone_identifiers as $tz) {
             if (strtolower($tz) == $timezone_l) {
                 debug("Time ReadData: Timezone exists: {$tz}\n");
                 $dateTime = new DateTime("now", new DateTimeZone($tz));
                 $item->add_note("time_time12", $dateTime->format("h:i"));
                 $item->add_note("time_time12ap", $dateTime->format("h:i A"));
                 $item->add_note("time_time24", $dateTime->format("H:i"));
                 $item->add_note("time_timezone", $tz);
                 $data[IN] = $dateTime->format("H");
                 $data_time = time();
                 $data[OUT] = $dateTime->format("i");
                 $matches++;
             }
         }
         if ($matches == 0) {
             warn("Time ReadData: Couldn't recognize {$timezone} as a valid timezone name [WMTIME02]\n");
         }
     } else {
         // some error code to go in here
         warn("Time ReadData: Couldn't recognize {$targetstring} \n");
     }
     debug("Time ReadData: Returning (" . ($data[IN] === NULL ? 'NULL' : $data[IN]) . "," . ($data[OUT] === NULL ? 'NULL' : $data[OUT]) . ",{$data_time})\n");
     return array($data[IN], $data[OUT], $data_time);
 }
 /**
  * Validate a Timezone name
  *
  * @param     string $timezone Time zone (e.g. 'Europe/London')
  *
  * @return     boolean                        Success or failure
  */
 public static function _validateTimeZone($timezone)
 {
     if (in_array($timezone, DateTimeZone::listIdentifiers())) {
         return true;
     }
     return false;
 }
Example #17
0
 /**
  * Short description of method initElements
  *
  * @access protected
  * @author Joel Bout, <*****@*****.**>
  * @return mixed
  */
 protected function initElements()
 {
     $langService = tao_models_classes_LanguageService::singleton();
     // Retrieve languages available for a GUI usage.
     $guiUsage = new core_kernel_classes_Resource(INSTANCE_LANGUAGE_USAGE_GUI);
     $guiOptions = array();
     foreach ($langService->getAvailableLanguagesByUsage($guiUsage) as $lang) {
         $guiOptions[tao_helpers_Uri::encode($lang->getUri())] = $lang->getLabel();
     }
     // Retrieve languages available for a Data usage.
     $dataUsage = new core_kernel_classes_Resource(INSTANCE_LANGUAGE_USAGE_DATA);
     $dataOptions = array();
     foreach ($langService->getAvailableLanguagesByUsage($dataUsage) as $lang) {
         $dataOptions[tao_helpers_Uri::encode($lang->getUri())] = $lang->getLabel();
     }
     $uiLangElement = tao_helpers_form_FormFactory::getElement('ui_lang', 'Combobox');
     $uiLangElement->setDescription(__('Interface language'));
     $uiLangElement->setOptions($guiOptions);
     $this->form->addElement($uiLangElement);
     $dataLangElement = tao_helpers_form_FormFactory::getElement('data_lang', 'Combobox');
     $dataLangElement->setDescription(__('Data language'));
     $dataLangElement->setOptions($dataOptions);
     $this->form->addElement($dataLangElement);
     $tzElement = tao_helpers_form_FormFactory::getElement('timezone', 'Combobox');
     $tzElement->setDescription(__('Time zone'));
     $options = array();
     foreach (DateTimeZone::listIdentifiers() as $id) {
         $options[$id] = $id;
     }
     $tzElement->setOptions($options);
     $this->form->addElement($tzElement);
 }
Example #18
0
 public static function getTimeZoneData()
 {
     $regions = array('Africa' => DateTimeZone::AFRICA, 'America' => DateTimeZone::AMERICA, 'Antarctica' => DateTimeZone::ANTARCTICA, 'Aisa' => DateTimeZone::ASIA, 'Atlantic' => DateTimeZone::ATLANTIC, 'Europe' => DateTimeZone::EUROPE, 'Indian' => DateTimeZone::INDIAN, 'Pacific' => DateTimeZone::PACIFIC);
     $result = array();
     foreach ($regions as $mask) {
         $zones = DateTimeZone::listIdentifiers($mask);
         $zones = self::prepareZones($zones);
         $i = 0;
         foreach ($zones as $zone) {
             $i++;
             $continent = $zone['continent'];
             $city = $zone['city'];
             $subcity = $zone['subcity'];
             $p = $zone['p'];
             $timeZone = $zone['time_zone'];
             if ($city) {
                 if ($subcity) {
                     $city = $city . '/' . $subcity;
                 }
                 $result[$continent][$timeZone] = "(UTC " . $p . ") " . str_replace('_', ' ', $city);
             }
         }
     }
     return $result;
 }
 /**
  * Shows the general settings form.
  *
  * @param array $variables
  */
 public function actionGeneralSettings(array $variables = array())
 {
     if (empty($variables['info'])) {
         $variables['info'] = Craft::getInfo();
     }
     // Assemble the timezone options array
     // (Technique adapted from http://stackoverflow.com/a/7022536/1688568)
     $variables['timezoneOptions'] = array();
     $utc = new DateTime();
     $offsets = array();
     $timezoneIds = array();
     $includedAbbrs = array();
     foreach (\DateTimeZone::listIdentifiers() as $timezoneId) {
         $timezone = new \DateTimeZone($timezoneId);
         $transition = $timezone->getTransitions($utc->getTimestamp(), $utc->getTimestamp());
         $abbr = $transition[0]['abbr'];
         $offset = round($timezone->getOffset($utc) / 60);
         if ($offset) {
             $hour = floor($offset / 60);
             $minutes = floor(abs($offset) % 60);
             $format = sprintf('%+d', $hour);
             if ($minutes) {
                 $format .= ':' . sprintf('%02u', $minutes);
             }
         } else {
             $format = '';
         }
         $offsets[] = $offset;
         $timezoneIds[] = $timezoneId;
         $includedAbbrs[] = $abbr;
         $variables['timezoneOptions'][$timezoneId] = 'UTC' . $format . ($abbr != 'UTC' ? " ({$abbr})" : '') . ($timezoneId != 'UTC' ? ' - ' . $timezoneId : '');
     }
     array_multisort($offsets, $timezoneIds, $variables['timezoneOptions']);
     $this->renderTemplate('settings/general/index', $variables);
 }
Example #20
0
/**
 * @brief Return timezones grouped (primarily) by continent.
 *
 * @return array
 */
function get_timezones()
{
    $timezone_identifiers = DateTimeZone::listIdentifiers();
    usort($timezone_identifiers, 'timezone_cmp');
    $continent = '';
    $continents = array();
    foreach ($timezone_identifiers as $value) {
        $ex = explode("/", $value);
        if (count($ex) > 1) {
            $continent = t($ex[0]);
            if (count($ex) > 2) {
                $city = substr($value, strpos($value, '/') + 1);
            } else {
                $city = $ex[1];
            }
        } else {
            $city = $ex[0];
            $continent = t('Miscellaneous');
        }
        $city = str_replace('_', ' ', t($city));
        if (!x($continents, $ex[0])) {
            $continents[$ex[0]] = array();
        }
        $continents[$continent][$value] = $city;
    }
    return $continents;
}
Example #21
0
 /**
  * Get a list of localized timezone names
  *
  * @return array
  */
 public static function getList()
 {
     $xoops = \Xoops::getInstance();
     $locale = \Xoops\Locale::getCurrent();
     $key = ['system', 'lists', 'timezone', $locale];
     //$xoops->cache()->delete($key);
     $timeZones = $xoops->cache()->cacheRead($key, function () {
         $timeZones = array();
         $territories = Territory::getContinentsAndCountries();
         $maxLen = 0;
         $utcDtz = new \DateTimeZone('UTC');
         foreach ($territories as $byContinent) {
             $continent = $byContinent['name'];
             foreach ($byContinent['children'] as $cCode => $cName) {
                 $allZones = $utcDtz->listIdentifiers(\DateTimeZone::PER_COUNTRY, $cCode);
                 foreach ($allZones as $zone) {
                     $maxLen = max(strlen($zone), $maxLen);
                     $name = Calendar::getTimezoneExemplarCity($zone);
                     if (!isset($timeZones[$zone]) && !empty($name)) {
                         $timeZones[$zone] = $continent . '/' . $name;
                     }
                 }
             }
         }
         \XoopsLocale::asort($timeZones);
         $default = array('UTC' => Calendar::getTimezoneNameNoLocationSpecific(new \DateTimeZone('GMT')));
         $timeZones = array_merge($default, $timeZones);
         return $timeZones;
     });
     return $timeZones;
 }
Example #22
0
 /**
  * Validate a Timezone name
  *
  * @param	 string		$timezone			Time zone (e.g. 'Europe/London')
  * @return	 boolean						Success or failure
  */
 public static function _validateTimeZone($timezone)
 {
     if (in_array($timezone, DateTimeZone::listIdentifiers())) {
         return TRUE;
     }
     return FALSE;
 }
Example #23
0
 /**
  * Method to get the time zone field option groups.
  *
  * @return  array  The field option objects as a nested array in groups.
  *
  * @since   1.0
  */
 protected function getGroups()
 {
     $groups = array();
     // Get the list of time zones from the server.
     $zones = \DateTimeZone::listIdentifiers();
     // Build the group lists.
     foreach ($zones as $zone) {
         // Time zones not in a group we will ignore.
         if (strpos($zone, '/') === false) {
             continue;
         }
         // Get the group/locale from the timezone.
         list($group, $locale) = explode('/', $zone, 2);
         // Only use known groups.
         if (in_array($group, self::$zones)) {
             // Initialize the group if necessary.
             if (!isset($groups[$group])) {
                 $groups[$group] = array();
             }
             // Only add options where a locale exists.
             if (!empty($locale)) {
                 $groups[$group][$zone] = Select::option($zone, str_replace('_', ' ', $locale), 'value', 'text', false);
             }
         }
     }
     // Sort the group lists.
     ksort($groups);
     foreach ($groups as &$location) {
         sort($location);
     }
     // Merge any additional groups in the XML definition.
     $groups = array_merge(parent::getGroups(), $groups);
     return $groups;
 }
Example #24
0
    /**
     * Returns the timezone choices.
     *
     * The choices are generated from the ICU function
     * \DateTimeZone::listIdentifiers(). They are cached during a single request,
     * so multiple timezone fields on the same page don't lead to unnecessary
     * overhead.
     *
     * @return array The timezone choices
     */
    public function getChoices()
    {
        if (null !== static::$timezones) {
            return static::$timezones;
        }

        static::$timezones = array();
        foreach (\DateTimeZone::listIdentifiers() as $timezone) {
            $parts = explode('/', $timezone);

            if (count($parts) > 2) {
                $region = $parts[0];
                $name = $parts[1].' - '.$parts[2];
            } else if (count($parts) > 1) {
                $region = $parts[0];
                $name = $parts[1];
            } else {
                $region = 'Other';
                $name = $parts[0];
            }

            if (!isset(static::$timezones[$region])) {
                static::$timezones[$region] = array();
            }

            static::$timezones[$region][$timezone] = str_replace('_', ' ', $name);
        }

        return static::$timezones;
    }
 /**
  * Returns the timezone choices
  *
  * The choices are generated from the ICU function
  * \DateTimeZone::listIdentifiers(). They are cached during a single request,
  * so multiple timezone fields on the same page don't lead to unnecessary
  * overhead.
  *
  * @return array  The timezone choices
  */
 protected static function getTimezoneChoices()
 {
     if (count(self::$timezones) == 0) {
         foreach (\DateTimeZone::listIdentifiers() as $timezone) {
             $parts = explode('/', $timezone);
             if (count($parts) > 2) {
                 $region = $parts[0];
                 $name = $parts[1] . ' - ' . $parts[2];
             } else {
                 if (count($parts) > 1) {
                     $region = $parts[0];
                     $name = $parts[1];
                 } else {
                     $region = 'Other';
                     $name = $parts[0];
                 }
             }
             if (!isset(self::$timezones[$region])) {
                 self::$timezones[$region] = array();
             }
             self::$timezones[$region][$timezone] = str_replace('_', ' ', $name);
         }
     }
     return self::$timezones;
 }
Example #26
0
 function fetchElement($name, $value, &$node, $control_name)
 {
     if (class_exists("DateTimeZone")) {
         $zones = DateTimeZone::listIdentifiers();
         static $options;
         if (!isset($options)) {
             $options = array();
             $options[] = JHTML::_('select.option', '', '- ' . JText::_('SELECT_TIMEZONE') . ' -');
             foreach ($zones as $zone) {
                 if (strpos($zone, "/") === false && strpos($zone, "UTC") === false) {
                     continue;
                 }
                 if (strpos($zone, "Etc") === 0) {
                     continue;
                 }
                 $options[] = JHTML::_('select.option', $zone, $zone);
             }
         }
         return JHTML::_('select.genericlist', $options, '' . $control_name . '[' . $name . ']', 'class="inputbox"', 'value', 'text', $value, $control_name . $name);
     } else {
         $size = $node->attributes('size') ? 'size="' . $node->attributes('size') . '"' : '';
         $class = $node->attributes('class') ? 'class="' . $node->attributes('class') . '"' : 'class="text_area"';
         /*
          * Required to avoid a cycle of encoding &
          * html_entity_decode was used in place of htmlspecialchars_decode because
          * htmlspecialchars_decode is not compatible with PHP 4
          */
         $value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES), ENT_QUOTES);
         return '<input type="text" name="' . $control_name . '[' . $name . ']" id="' . $control_name . $name . '" value="' . $value . '" ' . $class . ' ' . $size . ' />';
     }
 }
Example #27
0
function generateTimezoneList()
{
    $regions = array(DateTimeZone::AFRICA, DateTimeZone::AMERICA, DateTimeZone::ANTARCTICA, DateTimeZone::ASIA, DateTimeZone::ATLANTIC, DateTimeZone::AUSTRALIA, DateTimeZone::EUROPE, DateTimeZone::INDIAN, DateTimeZone::PACIFIC);
    $timezones = [];
    foreach ($regions as $region) {
        $timezones = array_merge($timezones, DateTimeZone::listIdentifiers($region));
    }
    $timezone_offsets = [];
    foreach ($timezones as $timezone) {
        $tz = new DateTimeZone($timezone);
        $utc = new DateTimeZone('UTC');
        $timezone_offsets[$timezone] = $tz->getOffset(new DateTime('now', $utc));
    }
    // sort timezone by timezone name
    ksort($timezone_offsets);
    $timezone_list = [];
    foreach ($timezone_offsets as $timezone => $offset) {
        $offset_prefix = $offset < 0 ? '-' : '+';
        $offset_formatted = gmdate('H:i', abs($offset));
        $pretty_offset = "UTC{$offset_prefix}{$offset_formatted}";
        $split = explode("/", $timezone);
        $timezone_list[$timezone] = "{$split['1']}/{$split['0']} ({$pretty_offset})";
    }
    asort($timezone_list);
    return $timezone_list;
}
Example #28
0
 protected function _beforeSave()
 {
     if (!in_array($this->getValue(), DateTimeZone::listIdentifiers())) {
         Mage::throwException(Mage::helper('adminhtml')->__('Invalid timezone'));
     }
     return $this;
 }
    function render_field($field)
    {
        /*
         *  Create a select dropdown with all available timezones
         */
        $utc = new DateTimeZone('UTC');
        $dt = new DateTime('now', $utc);
        ?>
        <select name="<?php 
        echo esc_attr($field['name']);
        ?>
">
            <?php 
        foreach (\DateTimeZone::listIdentifiers() as $tz) {
            $current_tz = new \DateTimeZone($tz);
            $transition = $current_tz->getTransitions($dt->getTimestamp(), $dt->getTimestamp());
            $abbr = $transition[0]['abbr'];
            $is_selected = trim($field['value']) === trim($tz) ? ' selected="selected"' : '';
            ?>
                <option value="<?php 
            echo $tz;
            ?>
"<?php 
            echo $is_selected;
            ?>
><?php 
            echo $tz . ' (' . $abbr . ')';
            ?>
</option>
            <?php 
        }
        ?>
        </select>
    <?php 
    }
Example #30
-1
 /**
  * @inheritdoc
  */
 public function run()
 {
     $timeZones = [];
     $timeZonesOutput = [];
     $now = new \DateTime('now', new \DateTimeZone('UTC'));
     foreach (\DateTimeZone::listIdentifiers(\DateTimeZone::ALL) as $timeZone) {
         $now->setTimezone(new \DateTimeZone($timeZone));
         $timeZones[] = [$now->format('P'), $timeZone];
     }
     if ($this->sortBy == static::SORT_OFFSET) {
         array_multisort($timeZones);
     }
     foreach ($timeZones as $timeZone) {
         $content = preg_replace_callback("/{\\w+}/", function ($matches) use($timeZone) {
             switch ($matches[0]) {
                 case '{name}':
                     return $timeZone[1];
                 case '{offset}':
                     return $timeZone[0];
                 default:
                     return $matches[0];
             }
         }, $this->template);
         $timeZonesOutput[$timeZone[1]] = $content;
     }
     echo Html::activeDropDownList($this->model, $this->attribute, $timeZonesOutput, $this->options);
 }