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); }
public function testConstruct() { $calendar = new Calendar('America/Regina'); $tz = new \DateTimeZone($calendar->getTimezoneId()); $dt = new \DateTime('now', $tz); $this->assertEquals(date_default_timezone_get(), $calendar->getTimezoneId()); $this->assertEquals($dt->format('T'), $calendar->getTimezoneName()); $this->assertEquals($tz->getOffset(new \DateTime()), $calendar->getTimezoneOffsetStart()); $this->assertEquals($tz->getOffset(new \DateTime()), $calendar->getTimezoneOffsetEnd()); }
/** * @param null $timezoneId */ public function __construct($timezoneId = null) { $tz = null === $timezoneId ? date_default_timezone_get() : $timezoneId; $this->setTimezoneId($tz); // Create a new \DateTime in the default timezone $t = new \DateTimeZone($this->getTimezoneId()); $d = new \DateTime('now', $t); $polarity = $t->getOffset($d) / 3600 === 0 ? '' : $t->getOffset($d) / 3600 < 0 ? '-' : '+'; $this->setTimezoneName($d->format('T')); $this->setTimezoneOffsetStart($polarity . gmdate('hi', $t->getOffset($d))); $this->setTimezoneOffsetEnd($polarity . gmdate('hi', $t->getOffset($d))); $this->events = new ArrayCollection(); return $this; }
/** * 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]; }
/** * 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; } }
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>'; } }
/** * 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()); } }
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; }
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); }
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; }
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 }
/** * 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); }
public static function getTimeZoneOffset() { $oTimeZoneUtc = new DateTimeZone('UTC'); $oTimeZoneLocal = new DateTimeZone(date_default_timezone_get()); $oDateTime = new DateTime('now', $oTimeZoneUtc); return $oTimeZoneLocal->getOffset($oDateTime); }
public static function timezoneList() { $tmp = array(); $timezone_identifiers_list = timezone_identifiers_list(); foreach ($timezone_identifiers_list as $timezone_identifier) { $date_time_zone = new DateTimeZone($timezone_identifier); $date_time = new DateTime('now', $date_time_zone); $hours = floor($date_time_zone->getOffset($date_time) / 3600); $mins = floor(($date_time_zone->getOffset($date_time) - $hours * 3600) / 60); $hours = 'GMT' . ($hours < 0 ? $hours : '+' . $hours); $mins = $mins > 0 ? $mins : '0' . $mins; $text = str_replace("_", " ", $timezone_identifier); $tmp[$text . ' (' . $hours . ':' . $mins . ')'] = $timezone_identifier; } return $tmp; }
public static function getTimezoneOffset($remoteTz, $originTz) { if (is_null($originTz)) { $originTz = date_default_timezone_get(); if (!is_string($originTz)) { return false; } } if (is_null($remoteTz)) { $remoteTz = date_default_timezone_get(); if (!is_string($remoteTz)) { return false; } } if (get_class($remoteTz) == 'DateTimeZone') { $remoteDtz = $remoteTz; } else { $remoteDtz = new DateTimeZone($remoteTz); } if (get_class($originTz) == 'DateTimeZone') { $originDtz = $originTz; } else { $originDtz = new DateTimeZone($originTz); } $originDt = new DateTime('now', $originDtz); $remoteDt = new DateTime('now', $remoteDtz); return $originDtz->getOffset($originDt) - $remoteDtz->getOffset($remoteDt); }
/** * 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; }
/** * 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); }
/** * 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); * */ } } }
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; }
/** * 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; }
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; }
/** * 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; }
/** * 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; }
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; }
/** * 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> (' . $objDb->ErrorMsg() . ')</i>'; unset($objDb); } return false; } }
/** Return additional information for specified Unix timezone @return array @param $id string @private **/ private static function tzdata($id) { $ref = new DateTimeZone($id); $loc = $ref->getLocation(); $now = time(); $trn = $ref->getTransitions($now, $now); return array('offset' => $ref->getOffset(new DateTime('now', new DateTimeZone('GMT'))) / 3600, 'country' => $loc['country_code'], 'latitude' => $loc['latitude'], 'longitude' => $loc['longitude'], 'dst' => $trn[0]['isdst']); }
/** * 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); }
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); }
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 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; }