Example #1
1
 public function testUsingYiiTimeZoneSwitcherWithPhpTimeFunction()
 {
     $oldTimeZone = Yii::app()->getTimeZone();
     $dateTimeUtc = new DateTime();
     $timeStamp = time();
     //always UTC regardless of server timezone or any timezone setting.
     Yii::app()->setTimeZone('UTC');
     $dateStamp = date("Y-m-d G:i", $timeStamp);
     Yii::app()->setTimeZone('America/Chicago');
     $dateStamp2 = date("Y-m-d G:i", $timeStamp);
     Yii::app()->setTimeZone('America/New_York');
     $timeZoneObject = new DateTimeZone('America/New_York');
     $offset = $timeZoneObject->getOffset(new DateTime());
     $this->assertTrue($offset == -18000 || $offset == -14400);
     $newYorkTimeZone = new DateTimeZone(date_default_timezone_get());
     $offset1 = $newYorkTimeZone->getOffset($dateTimeUtc);
     $offset2 = timezone_offset_get($newYorkTimeZone, $dateTimeUtc);
     $this->assertEquals($offset, $offset1);
     $this->assertEquals($offset, $offset2);
     if ($offset == -18000) {
         $offsetHours = 6;
     } else {
         $offsetHours = 5;
     }
     $dateStamp3 = date("Y-m-d G:i", $timeStamp);
     $this->assertEquals(strtotime($dateStamp), strtotime($dateStamp2) + 3600 * $offsetHours);
     // + 5 from GMT or +6 depending on DST
     $this->assertEquals(strtotime($dateStamp3), strtotime($dateStamp2) + 3600 * 1);
     // + 1 from NY
     //Use retrieved offset based on timezone.
     Yii::app()->setTimeZone($oldTimeZone);
 }
Example #2
0
 /**
  * Get the offset time between from timezone and to timezone.
  * @param        string $from_timezone Timezone departure
  * @param        string $to_timezone   Timezone arrival
  * @return       seconds                Timezone offset
  */
 public static function getOffset($from_timezone = "", $to_timezone = "")
 {
     if ($from_timezone === "" || $to_timezone === "") {
         return 0;
     }
     try {
         // Create two timezone objects, one for Singapore (Taiwan) and one for
         // Tokyo (Jakarta)
         $dateTimeFromZone = new \DateTimeZone($from_timezone);
         $dateTimeToZone = new \DateTimeZone($to_timezone);
         $date = (new \DateTime())->format('Y-m-d H:i:s');
         $datTimeFrom = new \DateTime($date, $dateTimeFromZone);
         $dateTimeTo = new \DateTime($date, $dateTimeToZone);
         // Calculate the GMT offset for the date/time contained in the $datTimeFrom
         // object, but using the timezone rules as defined for Tokyo
         // ($dateTimeToZone).
         $timeOffset = $dateTimeToZone->getOffset($datTimeFrom);
         $timeOffset2 = $dateTimeFromZone->getOffset($dateTimeTo);
         // Should show int(32400) (for dates after Sat Sep 8 01:00:00 1951 JST).
         $offset = $timeOffset - $timeOffset2;
         return $offset;
     } catch (\Exception $e) {
         return 0;
     }
 }
 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 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 #5
0
 protected function _timezone()
 {
     $element = new Zend_Form_Element_Select('timezone');
     $element->setLabel('Timezone')->addDecorators($this->_decorators)->setRequired(true)->setAttrib('class', 'span4');
     $timezones = array();
     $timezoneIdentifiers = DateTimeZone::listIdentifiers();
     foreach ($timezoneIdentifiers as $timezone) {
         if (preg_match('/^(Africa|America|Antarctica|Asia|Atlantic|Europe|Indian|Pacific)\\//', $timezone)) {
             $ex = explode('/', $timezone);
             $city = isset($ex[2]) ? $ex[1] . ' - ' . $ex[2] : $ex[1];
             $name = $ex[0];
             $timezones[$name][$timezone] = $city;
             $dateTimeZoneGmt = new DateTimeZone('GMT');
             $dateTimeZone = new DateTimeZone($timezone);
             $dateTimeGmt = new DateTime("now", $dateTimeZoneGmt);
             $timeOffset = $dateTimeZone->getOffset($dateTimeGmt);
             $gmt = $timeOffset / 3600;
             if ($gmt == 0) {
                 $gmt = ' 00';
             } elseif ($gmt > 0 && $gmt < 10) {
                 $gmt = '+0' . $gmt;
             } elseif ($gmt >= 10) {
                 $gmt = '+' . $gmt;
             } elseif ($gmt < 0 && $gmt > -10) {
                 $gmt = '-0' . abs($gmt);
             }
             $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' (GMT ' . $gmt . ':00)';
         }
     }
     $element->addMultiOptions($timezones);
     return $element;
 }
Example #6
0
 public function __construct($tqx, $tq, $tqrt, $tz, $locale, $extra = NULL)
 {
     $this->response = array('status' => 'ok');
     $this->params = array('version' => '0.6', 'sig' => '', 'responseHandler' => 'google.visualization.Query.setResponse');
     if ($extra) {
         foreach ($extra as $key => $value) {
             $this->params[$key] = $value;
         }
     }
     if ($tqx) {
         foreach (explode(';', $tqx) as $kvpair) {
             $kva = explode(':', $kvpair, 2);
             if (count($kva) == 2) {
                 $this->params[$kva[0]] = $kva[1];
             }
         }
     }
     if (get_magic_quotes_gpc()) {
         $tq = stripslashes($tq);
     }
     $this->debug = $extra && $extra['debug'];
     $this->tq = $tq;
     $this->tqrt = $tqrt;
     $this->tz = $tz;
     $this->locale = $locale;
     $timezone = new DateTimeZone($tz);
     $date = new DateTime("", $timezone);
     $this->gmt_offset = $timezone->getOffset($date);
 }
Example #7
0
function generate_timezone_list()
{
    static $regions = array(DateTimeZone::AFRICA, DateTimeZone::AMERICA, DateTimeZone::ANTARCTICA, DateTimeZone::ASIA, DateTimeZone::ATLANTIC, DateTimeZone::AUSTRALIA, DateTimeZone::EUROPE, DateTimeZone::INDIAN, DateTimeZone::PACIFIC);
    $timezones = array();
    foreach ($regions as $region) {
        $timezones = array_merge($timezones, DateTimeZone::listIdentifiers($region));
    }
    $timezone_offsets = array();
    foreach ($timezones as $timezone) {
        $tz = new DateTimeZone($timezone);
        $timezone_offsets[$timezone] = $tz->getOffset(new DateTime());
    }
    // sort timezone by timezone name
    ksort($timezone_offsets);
    $timezone_list = array();
    foreach ($timezone_offsets as $timezone => $offset) {
        $offset_prefix = $offset < 0 ? '-' : '+';
        $offset_formatted = gmdate('H:i', abs($offset));
        $pretty_offset = "UTC{$offset_prefix}{$offset_formatted}";
        $t = new DateTimeZone($timezone);
        $c = new DateTime(null, $t);
        $current_time = $c->format('g:i A');
        $timezone_list["({$pretty_offset}) {$timezone}"] = "{$timezone} - {$current_time} ({$pretty_offset})";
    }
    return $timezone_list;
}
Example #8
0
 /**
  * Returns the offset (in seconds) between two time zones.
  * @see     http://php.net/timezones
  *
  * @param   string          timezone that to find the offset of
  * @param   string|boolean  timezone used as the baseline
  * @return  integer
  */
 public static function offset($remote, $local = YES, $alt_format = false)
 {
     static $offsets;
     // Default values
     $remote = (string) $remote;
     $local = $local === YES ? date_default_timezone_get() : (string) $local;
     // Cache key name
     $cache = $remote . $local;
     if (empty($offsets[$cache])) {
         // Create timezone objects
         $remote = new DateTimeZone($remote);
         $local = new DateTimeZone($local);
         // Create date objects from timezones
         $time_there = new DateTime('now', $remote);
         $time_here = new DateTime('now', $local);
         // Find the offset
         $offset = $remote->getOffset($time_there) - $local->getOffset($time_here);
         // Return offset in +3:00 format
         if ($alt_format) {
             $offset = $offset / 60;
             $hours = floor($offset / 60);
             $min = str_pad(abs($offset % 60), 2, 0);
             if ($hours > 0) {
                 $hours = '+' . $hours;
             }
             $offsets[$cache] = $hours . ':' . $min;
         } else {
             $offsets[$cache] = $offset;
         }
     }
     return $offsets[$cache];
 }
Example #9
0
/**
 * Return server timezone int.
 *
 * @param	string	$refgmtdate		Reference period for timezone (timezone differs on winter and summer. May be 'now', 'winter' or 'summer')
 * @return 	int						An offset in hour (+1 for Europe/Paris on winter and +2 for Europe/Paris on summer)
 */
function getServerTimeZoneInt($refgmtdate = 'now')
{
    global $conf;
    if (method_exists('DateTimeZone', 'getOffset')) {
        // Method 1 (include daylight)
        $gmtnow = dol_now('gmt');
        $yearref = dol_print_date($gmtnow, '%Y');
        $monthref = dol_print_date($gmtnow, '%m');
        $dayref = dol_print_date($gmtnow, '%d');
        if ($refgmtdate == 'now') {
            $newrefgmtdate = $yearref . '-' . $monthref . '-' . $dayref;
        } elseif ($refgmtdate == 'summer') {
            $newrefgmtdate = $yearref . '-08-01';
        } else {
            $newrefgmtdate = $yearref . '-01-01';
        }
        $newrefgmtdate .= 'T00:00:00+00:00';
        $localtz = new DateTimeZone(getServerTimeZoneString());
        $localdt = new DateTime($newrefgmtdate, $localtz);
        $tmp = -1 * $localtz->getOffset($localdt);
        //print $refgmtdate.'='.$tmp;
    } else {
        $tmp = 0;
        dol_print_error('', 'PHP version must be 5.3+');
    }
    $tz = round(($tmp < 0 ? 1 : -1) * abs($tmp / 3600));
    return $tz;
}
 /**
  * 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);
 }
 private static function getTimezoneData($timezone_identifier)
 {
     // I'm very shame of that code but now i cannot create something better due
     // php hasn't a smart API (even after they have
     // rewrote datetime functions).
     // Here we should find the offset  for the provided timezone and determine
     // whether the timezone has the DST offset ever.
     // We cannot use date("I") due it depends on current time (if the current time
     // is in winter, we 'll skip the zone)
     // so the best safe (but not fast) practice is to scan all tz transitions
     $timezone = new DateTimeZone($timezone_identifier);
     $current_date = new DateTime("now", $timezone);
     $current_ts = strtotime($current_date->format(DATE_W3C));
     $data = array("offset" => 0, "dst" => false);
     $transitions = $timezone->getTransitions();
     foreach ($transitions as &$transition) {
         $tt = new DateTime($transition['time'], $timezone);
         $ts = strtotime($tt->format(DATE_W3C));
         if ($ts < $current_ts) {
             continue;
         }
         if (!$transition['isdst']) {
             $transition = next($transitions);
         }
         $data['dst'] = $transition['isdst'];
         $data['offset'] = self::makeOffset($transition);
         break;
     }
     return $data;
 }
Example #12
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 #13
0
 function generate_timezone_list()
 {
     $the_list = array();
     static $regions = array(DateTimeZone::AFRICA, DateTimeZone::AMERICA, DateTimeZone::ANTARCTICA, DateTimeZone::ASIA, DateTimeZone::ATLANTIC, DateTimeZone::AUSTRALIA, DateTimeZone::EUROPE, DateTimeZone::INDIAN, DateTimeZone::PACIFIC);
     $timezones = array();
     foreach ($regions as $region) {
         $timezones = array_merge($timezones, DateTimeZone::listIdentifiers($region));
     }
     $timezone_offsets = array();
     foreach ($timezones as $timezone) {
         $tz = new DateTimeZone($timezone);
         $timezone_offsets[$timezone] = $tz->getOffset(new DateTime());
     }
     // sort timezone by timezone name
     ksort($timezone_offsets);
     $timezone_list = array();
     foreach ($timezone_offsets as $timezone => $offset) {
         $offset_prefix = $offset < 0 ? '-' : '+';
         $offset_formatted = gmdate('H:i', abs($offset));
         $pretty_offset = "UTC{$offset_prefix}{$offset_formatted}";
         $t = new DateTimeZone($timezone);
         $c = new DateTime(null, $t);
         $current_time = $c->format('g:i A');
         $zone_abbrev = $c->format('T');
         $timezone_list[$timezone] = "({$zone_abbrev}) ({$pretty_offset}) {$timezone} - {$current_time}";
         $the_list_item['display'] = $timezone_list[$timezone];
         $the_list_item['offset'] = $pretty_offset;
         $the_list_item['zone'] = $timezone;
         $the_list_item['abbrev'] = $zone_abbrev . '(' . $pretty_offset . ')' . $timezone;
         array_push($the_list, $the_list_item);
     }
     return $the_list;
 }
Example #14
0
 /**
  * Returns server's offset from GMT in seconds.
  *
  * @return int Offset
  */
 function serverOffset()
 {
     $timezoneServer = new DateTimeZone(date_default_timezone_get());
     $timeServer = new DateTime('now', $timezoneServer);
     $offset = $timezoneServer->getOffset($timeServer);
     return $offset;
 }
Example #15
0
 /**
  * Connects to the database.
  *
  */
 protected function _connect()
 {
     parent::_connect();
     if (!$this->_initialized) {
         $this->_initialized = true;
         if ($this->_config['timezone']) {
             // Requires PHP 5.2+
             $dtz = new DateTimeZone($this->_config['timezone']);
             $offset = $dtz->getOffset(new DateTime('NOW')) / 60 / 60;
             if ($offset > 0) {
                 $offset = "+" . $offset;
             }
             /*
             echo "location: ".$dtz->getLocation()."<br />";
             echo "offset: ".$dtz->getOffset(new DateTime('NOW'))."<br />";
             echo "offset 2: ". $offset."<br />";
             echo "SET time_zone = '$offset:00'"."<br />";
             */
             $this->query("SET time_zone = '{$offset}:00';");
             //sprintf("SET time_zone = '%d:00'", $offset));
             /*
                             $timezone = new DateTimeZone($this->_config['timezone']);
                             $minutes = $timezone->getOffset(new DateTime('NOW')) / 60 / 60;
                             
                             
                             
                             //$offset = sprintf("SET time_zone = '%d:%2d'", $minutes / 60, $minutes % 60);
                             $offset = sprintf("SET time_zone = '%d:00'", $offset);
             *
             */
         }
     }
 }
Example #16
0
 /**
  * Get offset between a time zone and UTC time zone in seconds.
  *
  * @return integer
  */
 public function UTCTimeZoneOffset() : int
 {
     $originDateTime = new \DateTime('now', $this);
     $utcTimeZone = new \DateTimeZone('UTC');
     $utcDateTime = new \DateTime('now', $utcTimeZone);
     return $utcTimeZone->getOffset($utcDateTime) - $this->getOffset($originDateTime);
 }
Example #17
0
 /** 
  * Find the local time at the event...
  * @param $evt_offset integer Event's offset from UTC
  */
 private function _getEvtTime($evt_offset)
 {
     $here = new DateTimeZone(date_default_timezone_get());
     $hoffset = $here->getOffset(new DateTime("now", $here));
     $off = time() - $hoffset + $evt_offset * 3600;
     return $off;
 }
Example #18
0
 public static function getTimeZoneOffset()
 {
     $oTimeZoneUtc = new DateTimeZone('UTC');
     $oTimeZoneLocal = new DateTimeZone(date_default_timezone_get());
     $oDateTime = new DateTime('now', $oTimeZoneUtc);
     return $oTimeZoneLocal->getOffset($oDateTime);
 }
Example #19
0
	/**
	 * Returns the offset (in seconds) between two time zones. Use this to
	 * display dates to users in different time zones.
	 *
	 *     $seconds = Date::offset('America/Chicago', 'GMT');
	 *
	 * [!!] A list of time zones that PHP supports can be found at
	 * <http://php.net/timezones>.
	 *
	 * @param   string   timezone that to find the offset of
	 * @param   string   timezone used as the baseline
	 * @param   mixed    UNIX timestamp or date string
	 * @return  integer
	 */
	public static function offset($remote, $local = NULL, $now = NULL)
	{
		if ($local === NULL)
		{
			// Use the default timezone
			$local = date_default_timezone_get();
		}

		if (is_int($now))
		{
			// Convert the timestamp into a string
			$now = date(DateTime::RFC2822, $now);
		}

		// Create timezone objects
		$zone_remote = new DateTimeZone($remote);
		$zone_local  = new DateTimeZone($local);

		// Create date objects from timezones
		$time_remote = new DateTime($now, $zone_remote);
		$time_local  = new DateTime($now, $zone_local);

		// Find the offset
		$offset = $zone_remote->getOffset($time_remote) - $zone_local->getOffset($time_local);

		return $offset;
	}
Example #20
0
 public static function fetchSelect()
 {
     // Time zone configuration
     $utc = new \DateTimeZone('UTC');
     $dt = new \DateTime('now', $utc);
     $tz_options = array('UTC' => 'UTC', 'US/Pacific' => "Pacific Time (US & Canada)", 'US/Mountain' => "Mountain Time (US & Canada)", 'US/Central' => "Central Time (US & Canada)", 'US/Eastern' => "Eastern Time (US & Canada)", 'Canada/Atlantic' => "Atlantic Time (Canada)", 'Pacific/Midway' => "Midway Island", 'US/Samoa' => "Samoa", 'US/Hawaii' => "Hawaii", 'US/Alaska' => "Alaska", 'America/Tijuana' => "Tijuana", 'US/Arizona' => "Arizona", 'America/Chihuahua' => "Chihuahua", 'America/Mazatlan' => "Mazatlan", 'America/Mexico_City' => "Mexico City", 'America/Monterrey' => "Monterrey", 'Canada/Saskatchewan' => "Saskatchewan", 'US/East-Indiana' => "Indiana (East)", 'America/Bogota' => "Bogota", 'America/Lima' => "Lima", 'America/Caracas' => "Caracas", 'America/La_Paz' => "La Paz", 'America/Santiago' => "Santiago", 'Canada/Newfoundland' => "Newfoundland", 'America/Buenos_Aires' => "Buenos Aires", 'Atlantic/Stanley' => "Stanley", 'Atlantic/Azores' => "Azores", 'Atlantic/Cape_Verde' => "Cape Verde Is.", 'Africa/Casablanca' => "Casablanca", 'Europe/Dublin' => "Dublin", 'Europe/Lisbon' => "Lisbon", 'Europe/London' => "London", 'Africa/Monrovia' => "Monrovia", 'Europe/Amsterdam' => "Amsterdam", 'Europe/Belgrade' => "Belgrade", 'Europe/Berlin' => "Berlin", 'Europe/Bratislava' => "Bratislava", 'Europe/Brussels' => "Brussels", 'Europe/Budapest' => "Budapest", 'Europe/Copenhagen' => "Copenhagen", 'Europe/Ljubljana' => "Ljubljana", 'Europe/Madrid' => "Madrid", 'Europe/Paris' => "Paris", 'Europe/Prague' => "Prague", 'Europe/Rome' => "Rome", 'Europe/Sarajevo' => "Sarajevo", 'Europe/Skopje' => "Skopje", 'Europe/Stockholm' => "Stockholm", 'Europe/Vienna' => "Vienna", 'Europe/Warsaw' => "Warsaw", 'Europe/Zagreb' => "Zagreb", 'Europe/Athens' => "Athens", 'Europe/Bucharest' => "Bucharest", 'Africa/Cairo' => "Cairo", 'Africa/Harare' => "Harare", 'Europe/Helsinki' => "Helsinki", 'Europe/Istanbul' => "Istanbul", 'Asia/Jerusalem' => "Jerusalem", 'Europe/Kiev' => "Kyiv", 'Europe/Minsk' => "Minsk", 'Europe/Riga' => "Riga", 'Europe/Sofia' => "Sofia", 'Europe/Tallinn' => "Tallinn", 'Europe/Vilnius' => "Vilnius", 'Asia/Baghdad' => "Baghdad", 'Asia/Kuwait' => "Kuwait", 'Africa/Nairobi' => "Nairobi", 'Asia/Riyadh' => "Riyadh", 'Asia/Tehran' => "Tehran", 'Europe/Moscow' => "Moscow", 'Asia/Baku' => "Baku", 'Europe/Volgograd' => "Volgograd", 'Asia/Muscat' => "Muscat", 'Asia/Tbilisi' => "Tbilisi", 'Asia/Yerevan' => "Yerevan", 'Asia/Kabul' => "Kabul", 'Asia/Karachi' => "Karachi", 'Asia/Tashkent' => "Tashkent", 'Asia/Kolkata' => "Kolkata", 'Asia/Kathmandu' => "Kathmandu", 'Asia/Yekaterinburg' => "Ekaterinburg", 'Asia/Almaty' => "Almaty", 'Asia/Dhaka' => "Dhaka", 'Asia/Novosibirsk' => "Novosibirsk", 'Asia/Bangkok' => "Bangkok", 'Asia/Jakarta' => "Jakarta", 'Asia/Krasnoyarsk' => "Krasnoyarsk", 'Asia/Chongqing' => "Chongqing", 'Asia/Hong_Kong' => "Hong Kong", 'Asia/Kuala_Lumpur' => "Kuala Lumpur", 'Australia/Perth' => "Perth", 'Asia/Singapore' => "Singapore", 'Asia/Taipei' => "Taipei", 'Asia/Ulaanbaatar' => "Ulaan Bataar", 'Asia/Urumqi' => "Urumqi", 'Asia/Irkutsk' => "Irkutsk", 'Asia/Seoul' => "Seoul", 'Asia/Tokyo' => "Tokyo", 'Australia/Adelaide' => "Adelaide", 'Australia/Darwin' => "Darwin", 'Asia/Yakutsk' => "Yakutsk", 'Australia/Brisbane' => "Brisbane", 'Australia/Canberra' => "Canberra", 'Pacific/Guam' => "Guam", 'Australia/Hobart' => "Hobart", 'Australia/Melbourne' => "Melbourne", 'Pacific/Port_Moresby' => "Port Moresby", 'Australia/Sydney' => "Sydney", 'Asia/Vladivostok' => "Vladivostok", 'Asia/Magadan' => "Magadan", 'Pacific/Auckland' => "Auckland", 'Pacific/Fiji' => "Fiji");
     $tz_select_raw = array();
     foreach ($tz_options as $tz => $tz_display) {
         $current_tz = new \DateTimeZone($tz);
         $offset = $current_tz->getOffset($dt);
         $tz_select_raw[$offset][$tz] = $tz_display;
     }
     ksort($tz_select_raw);
     $tz_select = array();
     foreach ($tz_select_raw as $offset => $cities) {
         $offset_name = self::formatOffset($offset);
         $offset_key = key($cities);
         if (count($cities) > 5) {
             $cities = array_slice($cities, 0, 5);
             $offset_cities = implode(', ', $cities) . '...';
         } else {
             $offset_cities = implode(', ', $cities);
         }
         $tz_select[$offset_key] = $offset_name . ': ' . $offset_cities;
     }
     return $tz_select;
 }
    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 
    }
function timezonesFromCountryCode($country_code, $city_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
    arsort($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}";
        // clean up raw timezone
        $clean_timezone = User::cleanCity($raw_timezone);
        // echo back options to a select dropdown on workshop.php
        if ($city_name == $clean_timezone) {
            echo "<option value=\"{$raw_timezone}\" selected>(" . $pretty_offset . ") " . $clean_timezone . ' (' . $timezone_abbr . ')</option>';
        } else {
            echo "<option value=\"{$raw_timezone}\">(" . $pretty_offset . ") " . $clean_timezone . ' (' . $timezone_abbr . ')</option>';
        }
    }
    // end of: foreach
}
Example #23
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 #24
0
/**
 * Returns the database object.
 *
 * If none was created before, or if {link $newInstance} is true,
 * creates a new database object first.
 * In case of an error, the reference argument $errorMsg is set
 * to the error message.
 * @author  Comvation Development Team <*****@*****.**>
 * @access  public
 * @version 1.0.0
 * @param   string  $errorMsg       Error message
 * @param   boolean $newInstance    Force new instance
 * @global  array                   Language array
 * @global  array                   Database configuration
 * @global  integer                 ADODB fetch mode
 * @return  boolean                 True on success, false on failure
 */
function getDatabaseObject(&$errorMsg, $newInstance = false)
{
    global $_DBCONFIG, $ADODB_FETCH_MODE, $_CONFIG;
    static $objDatabase;
    if (is_object($objDatabase) && !$newInstance) {
        return $objDatabase;
    } else {
        // open db connection
        $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
        $objDb = ADONewConnection($_DBCONFIG['dbType']);
        @$objDb->Connect($_DBCONFIG['host'], $_DBCONFIG['user'], $_DBCONFIG['password'], $_DBCONFIG['database']);
        $errorNo = $objDb->ErrorNo();
        if ($errorNo != 0) {
            if ($errorNo == 1049) {
                $errorMsg = 'The database is unavailable';
            } else {
                $errorMsg = $objDb->ErrorMsg() . "<br />";
            }
            unset($objDb);
            return false;
        }
        if (!empty($_CONFIG['timezone'])) {
            if (!$objDb->Execute('SET TIME_ZONE="' . $_CONFIG['timezone'] . '"') && array_search($_CONFIG['timezone'], timezone_identifiers_list())) {
                //calculate and set the timezone offset if the mysql timezone tables aren't loaded
                $objDateTimeZone = new DateTimeZone($_CONFIG['timezone']);
                $objDateTime = new DateTime('now', $objDateTimeZone);
                $offset = $objDateTimeZone->getOffset($objDateTime);
                $offsetHours = round(abs($offset) / 3600);
                $offsetMinutes = round((abs($offset) - $offsetHours * 3600) / 60);
                $offsetString = ($offset > 0 ? '+' : '-') . ($offsetHours < 10 ? '0' : '') . $offsetHours . ':' . ($offsetMinutes < 10 ? '0' : '') . $offsetMinutes;
                $objDb->Execute('SET TIME_ZONE="' . $offsetString . '"');
            }
        }
        // Disable STRICT_TRANS_TABLES mode:
        $res = $objDb->Execute('SELECT @@sql_mode');
        if ($res->EOF) {
            $errorMsg = 'Database mode error';
            return;
        }
        $sqlModes = explode(',', $res->fields['@@sql_mode']);
        array_walk($sqlModes, 'trim');
        if (($index = array_search('STRICT_TRANS_TABLES', $sqlModes)) !== false) {
            unset($sqlModes[$index]);
        }
        $objDb->Execute('SET sql_mode = \'' . implode(',', $sqlModes) . '\'');
        if (empty($_DBCONFIG['charset']) || $objDb->Execute('SET NAMES ' . $_DBCONFIG['charset']) && $objDb) {
            if ($newInstance) {
                return $objDb;
            } else {
                $objDatabase = $objDb;
                return $objDb;
            }
        } else {
            $errorMsg = 'Cannot connect to database server<i>&nbsp;(' . $objDb->ErrorMsg() . ')</i>';
            unset($objDb);
        }
        return false;
    }
}
Example #25
0
 /**
  * Get the timezone offset between the given timezone and the local timezone
  *
  * @param      string  $remoteTimezone  The given timezone
  *
  * @return     int     The offset between local and given timezone in seconds
  */
 public static function getTimezoneOffset(string $remoteTimezone) : int
 {
     $originDateTimeZone = new \DateTimeZone(date_default_timezone_get());
     $remoteDateTimeZone = new \DateTimeZone($remoteTimezone);
     $originDateTime = new \DateTime('now', $originDateTimeZone);
     $remoteDateTime = new \DateTime('now', $remoteDateTimeZone);
     return $originDateTimeZone->getOffset($originDateTime) - $remoteDateTimeZone->getOffset($remoteDateTime);
 }
Example #26
0
 public static function getDateWithTimezoneOffset()
 {
     $this_tz_str = date_default_timezone_get();
     $this_tz = new DateTimeZone($this_tz_str);
     $now = new DateTime("now", $this_tz);
     $offset = $this_tz->getOffset($now);
     return time() + $offset;
 }
 function _date($format = "r", $timestamp = false, $timezone = false)
 {
     $userTimezone = new DateTimeZone(!empty($timezone) ? $timezone : 'GMT');
     $gmtTimezone = new DateTimeZone('GMT');
     $myDateTime = new DateTime($timestamp != false ? date("r", (int) $timestamp) : date("r"), $gmtTimezone);
     $offset = $userTimezone->getOffset($myDateTime);
     return date($format, ($timestamp != false ? (int) $timestamp : $myDateTime->format('U')) + $offset);
 }
 /**
  * 
  * @param string $pValue
  * @param \DateTimeZone $pDateTimeZone
  * @return \DateTime
  */
 public function fromString($pValue, \DateTimeZone $pDateTimeZone)
 {
     $lDateTime = new \DateTime($pValue, $pDateTimeZone);
     if ($lDateTime->getTimezone()->getName() !== $pDateTimeZone->getName()) {
         $lDateTime->setTimezone($pDateTimeZone);
     }
     return $lDateTime;
 }
 function timestamp_adjust($timestamp, $to_timezone)
 {
     $datetime_object = new DateTime("@" . $timestamp);
     $from_timezone_object = new DateTimeZone(date_default_timezone_get());
     $to_timezone_object = new DateTimeZone($to_timezone);
     $offset = $to_timezone_object->getOffset($datetime_object) - $from_timezone_object->getOffset($datetime_object);
     return $timestamp + $offset;
 }
Example #30
-20
 /**
  * @Route("/dodaj_zdarzenie", name="dodaj_zdarzenie", options={"expose"=true})
  * @param Request $request
  * @return Response
  */
 public function dodajZdarzenieAction(Request $request)
 {
     $time_zone = new \DateTimeZone('UTC');
     $time_zone->getName();
     $dane = new Zdarzenia();
     $start = new \DateTime($request->get('start'));
     //$start->createFromFormat('ATOM', $request->get('start'),$time_zone);
     $end = new \DateTime($request->get('end'));
     //$end->createFromFormat('ATOM', $request->get('end'),$time_zone);
     $dane->setTitle($request->get('title'));
     $dane->setDescription($request->get('description'));
     $dane->setLocation($request->get('location'));
     $dane->setContact($request->get('contact'));
     $dane->setUrl($request->get('url'));
     $dane->setStart($start);
     $dane->setEnd($end);
     $dane->setAlldayevent($request->get('alldayevent'));
     $em = $this->getDoctrine()->getManager();
     $em->persist($dane);
     $em->flush();
     $response = new \Symfony\Component\HttpFoundation\Response();
     $response->headers->set('Content-Type', 'application/json');
     $response->setContent(json_encode($dane));
     return $response;
 }