/**
  *
  * Possible bug was also detected: date_sunrise() seems to return date of the previous day:
  * https://bugs.php.net/bug.php?id=53148
  *
  * To avoid issues, only compare day agnostic formats:  $dt->format('Hi')
  *
  * @param \DateTime $dateTime
  * @param $method
  *
  * @return \DateTime
  */
 private function getChangeTime(\DateTime $dateTime, $method)
 {
     $location = $dateTime->getTimezone()->getLocation();
     $horizonShift = new \DateTime('now', $dateTime->getTimezone());
     $horizonShift->setTimestamp($method($dateTime->getTimestamp(), SUNFUNCS_RET_TIMESTAMP, $location['latitude'], $location['longitude'], ini_get("date.sunrise_zenith"), $dateTime->getOffset() / 3600));
     return $horizonShift;
 }
Example #2
0
 /**
  *
  */
 public function testSetTimezone()
 {
     $dt = new DateTime('2013-03-08 10:00:00');
     $dt->setTimezone('Europe/Berlin');
     $this->assertEquals('2013-03-08 11:00:00', $dt->format('Y-m-d H:i:s'));
     $this->assertEquals('Europe/Berlin', $dt->getTimezone()->getName());
     $dt->setTimezone(new \DateTimeZone('Indian/Mahe'), true);
     $this->assertEquals('2013-03-08 11:00:00', $dt->format('Y-m-d H:i:s'));
     $this->assertEquals('Indian/Mahe', $dt->getTimezone()->getName());
     $dt->setTimezone(null);
     $this->assertEquals('UTC', $dt->getTimezone()->getName());
 }
 public function toString(\DateTime $pDateTime, $pDateTimeZone)
 {
     if ($pDateTimeZone->getName() == $pDateTime->getTimezone()->getName()) {
         return $pDateTime->format('c');
     } else {
         $lDateTimeZone = $pDateTime->getTimezone();
         $pDateTime->setTimezone($pDateTimeZone);
         $lDateTimeString = $pDateTime->format('c');
         $pDateTime->setTimezone($lDateTimeZone);
         return $lDateTimeString;
     }
     return $pDateTime->format('c');
 }
Example #4
0
 /**
  * @param $format
  * @return bool|string
  */
 public function format($format)
 {
     // convert alias string
     if (in_array($format, array_keys($this->formats))) {
         $format = $this->formats[$format];
     }
     // if valid unix timestamp...
     if ($this->dateTime !== false) {
         return jDateTime::strftime($format, $this->dateTime->getTimestamp(), $this->dateTime->getTimezone());
     } else {
         return false;
     }
 }
 /**
  * getDateformat
  * @param string $dateFormat
  * @param string $timeFormat
  * @param string $locale
  * @param string $timezone
  * @param string $format
  * @return string
  **/
 public function getDateformat($dateFormat = 'medium', $timeFormat = 'medium', $locale = null, $timezone = null, $format = null)
 {
     $date = new \DateTime();
     $formatValues = array('none' => IntlDateFormatter::NONE, 'short' => IntlDateFormatter::SHORT, 'medium' => IntlDateFormatter::MEDIUM, 'long' => IntlDateFormatter::LONG, 'full' => IntlDateFormatter::FULL);
     $formatter = IntlDateFormatter::create($locale, $formatValues[$dateFormat], $formatValues[$timeFormat], $date->getTimezone()->getName(), IntlDateFormatter::GREGORIAN, $format);
     return strtoupper($formatter->getPattern());
 }
Example #6
0
 public static function getTimezoneSelectOptions()
 {
     $dateTimeObject = new \DateTime();
     $currentTimeZone = isset($_SESSION['config']) && !empty($_SESSION['config']['timezone']) ? $_SESSION['config']['timezone'] : $dateTimeObject->getTimezone()->getName();
     $timezoneSelectOptions = '';
     $timezones = \DateTimeZone::listIdentifiers(\DateTimeZone::ALL_WITH_BC);
     $lastGroup = '';
     foreach ($timezones as $timezone) {
         $timezoneParts = explode('/', $timezone);
         $curGroup = $timezoneParts[0];
         if ($curGroup != $lastGroup) {
             if ($lastGroup != '') {
                 $timezoneSelectOptions .= '</optgroup>';
             }
             $timezoneSelectOptions .= '<optgroup label="' . addslashes($curGroup) . '">';
             $lastGroup = $curGroup;
         }
         if ($timezone == $currentTimeZone) {
             $selected = ' selected="selected"';
         } else {
             $selected = '';
         }
         $timezoneSelectOptions .= '<option' . $selected . ' value="' . addslashes($timezone) . '">' . htmlspecialchars($timezone) . '</option>';
     }
     return $timezoneSelectOptions;
 }
Example #7
0
function main()
{
    $date = new DateTime("now");
    $date->setTimezone(new DateTimeZone('America/Los_Angeles'));
    $tz = $date->getTimezone();
    print $tz->getName() . "\n";
}
 /**
  * Returns new DateTime object
  * 
  * @param string|int|DateTime $_time
  * @param string|DateTimeZone $_timezone
  */
 public function __construct($_time = "now", $_timezone = NULL)
 {
     // allow to pass instanceof DateTime
     if ($_time instanceof DateTime) {
         if (!$_timezone) {
             $_timezone = $_time->getTimezone();
         } else {
             $_time = clone $_time;
             $_time->setTimezone($_timezone);
         }
         $time = $_time->format("Y-m-d H:i:s");
     } else {
         $time = is_numeric($_time) ? "@" . floor($_time) : $_time;
     }
     if ($_timezone) {
         if (!$_timezone instanceof DateTimeZone) {
             $_timezone = new DateTimeZone($_timezone);
         }
         parent::__construct($time, $_timezone);
     } else {
         parent::__construct($time);
     }
     // Normalize Timezonename, as sometimes +00:00 is taken
     if (is_numeric($_time)) {
         $this->setTimezone('UTC');
     }
 }
Example #9
0
 /**
  * convert a string into the required date format for the database
  * important: returned date is in german local time (mez)!
  * @param $string String the given string
  * @return string|null
  */
 public function parseDate($string)
 {
     $localTime = new DateTime();
     $date = strtotime($string);
     // format yyyy-mm-ddThh:ii:ssZ
     if ('z' === strpos(strtolower($string), -1, 1)) {
         $string = strtolower($string);
         $string = str_replace('z', '', $string);
         $string = str_replace('t', ' ', $string);
         $date = new DateTime($string, DateTimeZone::UTC);
         $date->setTimezone($localTime->getTimezone());
         $date = $date->format('Y-m-d H:i:s');
     } else {
         if ($date) {
             $date = date('Y-m-d H:i:s', $date);
             $date = new DateTime($date);
             $date = $date->format('Y-m-d H:i:s');
         }
     }
     if ($date && date('Y-m-d H:i:s') > $date) {
         return $date;
     }
     // if the date can not be parsed or is in future return the current date
     return date('Y-m-d H:i:s');
 }
Example #10
0
/**
 * Build and return the Countdown component.
 *
 * @since   1.0.0
 *
 * @param   array  $args  The args.
 *
 * @return  string        The HTML.
 */
function mm_countdown($args)
{
    $component = 'mm-countdown';
    // Set our defaults and use them as needed.
    $defaults = array('date' => '', 'time' => '', 'timezone' => '');
    $args = wp_parse_args((array) $args, $defaults);
    // Get clean param values.
    $date = $args['date'];
    $time = $args['time'];
    $timezone = $args['timezone'];
    // Enqueue pre-registerd 3rd party countdown script.
    wp_enqueue_script('mm-jquery-countdown');
    // Get Mm classes.
    $mm_classes = apply_filters('mm_components_custom_classes', '', $component, $args);
    // Create new date object.
    $date_obj = new DateTime($date . ' ' . $time . ' ' . $timezone);
    $utc_date_ojb = new DateTime($date . ' ' . $time);
    // Get timezone offset.
    $timezone_offset = $date_obj->getTimezone()->getOffset($utc_date_ojb) / 3600;
    // Pass data to JS as data attributes.
    $year = $date_obj->format('Y');
    $month = $date_obj->format('n');
    $day = $date_obj->format('j');
    $hour = $date_obj->format('G');
    $minute = $date_obj->format('i');
    $second = $date_obj->format('s');
    return sprintf('<div class="%s" data-year="%s" data-month="%s" data-day="%s" data-hour="%s" data-minute="%s" data-second="%s" data-timezone-offset="%s"></div>', esc_attr($mm_classes), esc_attr($year), esc_attr($month), esc_attr($day), esc_attr($hour), esc_attr($minute), esc_attr($second), esc_attr($timezone_offset));
}
 public function LatestTweetsList($limit = '5')
 {
     $conf = SiteConfig::current_site_config();
     if (empty($conf->TwitterName) || empty($conf->TwitterConsumerKey) || empty($conf->TwitterConsumerSecret) || empty($conf->TwitterAccessToken) || empty($conf->TwitterAccessTokenSecret)) {
         return new ArrayList();
     }
     $cache = SS_Cache::factory('LatestTweets_cache');
     if (!($results = unserialize($cache->load(__FUNCTION__)))) {
         $results = new ArrayList();
         require_once dirname(__FILE__) . '/tmhOAuth/tmhOAuth.php';
         require_once dirname(__FILE__) . '/tmhOAuth/tmhUtilities.php';
         $tmhOAuth = new tmhOAuth(array('consumer_key' => $conf->TwitterConsumerKey, 'consumer_secret' => $conf->TwitterConsumerSecret, 'user_token' => $conf->TwitterAccessToken, 'user_secret' => $conf->TwitterAccessTokenSecret, 'curl_ssl_verifypeer' => false));
         $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array('screen_name' => $conf->TwitterName, 'count' => $limit));
         $tweets = $tmhOAuth->response['response'];
         $json = new JSONDataFormatter();
         if (($arr = $json->convertStringToArray($tweets)) && is_array($arr) && isset($arr[0]['text'])) {
             foreach ($arr as $tweet) {
                 try {
                     $here = new DateTime(SS_Datetime::now()->getValue());
                     $there = new DateTime($tweet['created_at']);
                     $there->setTimezone($here->getTimezone());
                     $date = $there->Format('Y-m-d H:i:s');
                 } catch (Exception $e) {
                     $date = 0;
                 }
                 $results->push(new ArrayData(array('Text' => nl2br(tmhUtilities::entify_with_options($tweet, array('target' => '_blank'))), 'Date' => SS_Datetime::create_field('SS_Datetime', $date))));
             }
         }
         $cache->save(serialize($results), __FUNCTION__);
     }
     return $results;
 }
 /**
  * {@inheritdoc}
  */
 public function reverseTransform($rfc3339)
 {
     if (!is_string($rfc3339)) {
         throw new TransformationFailedException('Expected a string.');
     }
     if ('' === $rfc3339) {
         return;
     }
     try {
         $dateTime = new \DateTime($rfc3339);
     } catch (\Exception $e) {
         throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
     }
     if ($this->outputTimezone !== $dateTime->getTimezone()->getName()) {
         try {
             $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone));
         } catch (\Exception $e) {
             throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
         }
     }
     if (preg_match('/(\\d{4})-(\\d{2})-(\\d{2})/', $rfc3339, $matches)) {
         if (!checkdate($matches[2], $matches[3], $matches[1])) {
             throw new TransformationFailedException(sprintf('The date "%s-%s-%s" is not a valid date.', $matches[1], $matches[2], $matches[3]));
         }
     }
     return $dateTime;
 }
Example #13
0
 public static function castFromBuiltin(\DateTime $dt)
 {
     $newCls = new static();
     $newCls->setTimestamp($dt->getTimestamp());
     $newCls->setTimezone($dt->getTimezone());
     return $newCls;
 }
 /**
  * Implements what IntlDateFormatter::formatObject() is in PHP 5.5+
  *
  * @param \IntlCalendar|\DateTime $object
  * @param string|int|array|null $format
  * @param string|null $locale
  * @return string
  * @throws LocalizedException
  */
 protected function doFormatObject($object, $format = null, $locale = null)
 {
     $pattern = $dateFormat = $timeFormat = $calendar = null;
     if (is_array($format)) {
         list($dateFormat, $timeFormat) = $format;
     } elseif (is_numeric($format)) {
         $dateFormat = $format;
     } elseif (is_string($format) || null == $format) {
         $dateFormat = $timeFormat = \IntlDateFormatter::MEDIUM;
         $pattern = $format;
     } else {
         throw new LocalizedException(new Phrase('Format type is invalid'));
     }
     $timezone = $object->getTimezone();
     if ($object instanceof \IntlCalendar) {
         $timezone = $timezone->toDateTimeZone();
     }
     $timezone = $timezone->getName();
     if ($timezone === '+00:00') {
         $timezone = 'UTC';
     } elseif ($timezone[0] === '+' || $timezone[0] === '-') {
         // $timezone[0] is first symbol of string
         $timezone = 'GMT' . $timezone;
     }
     return (new \IntlDateFormatter($locale, $dateFormat, $timeFormat, $timezone, $calendar, $pattern))->format($object);
 }
Example #15
0
 public function actionCheck()
 {
     $dt = new \DateTime();
     echo 'Current date/time: ' . $dt->format('d-m-Y H:i:s');
     echo '<br />';
     echo 'Current timezone: ' . $dt->getTimezone()->getName();
 }
 public function actionCheck()
 {
     $dt = new \DateTime();
     echo '当前时间:' . $dt->format('Y-m-d H:i:s');
     echo "<br/>";
     echo "当前时区:" . $dt->getTimezone()->getname();
 }
 /**
  * @param \DateTime $dateTime
  * @return string
  */
 public function getDateStringFromDateTime(\DateTime $dateTime)
 {
     $savedTimeZone = $dateTime->getTimezone();
     $dateTime->setTimezone(new \DateTimeZone($this->targetSystemTimeZone));
     $restApiDateString = $dateTime->format($this->targetSystemDateFormat);
     $dateTime->setTimezone($savedTimeZone);
     return $restApiDateString;
 }
 /**
  * {@inheritDoc}
  *
  * @throws NotImplementedException  When time zone is different than UTC or GMT (Etc/GMT)
  */
 public function format(\DateTime $dateTime, $length)
 {
     $timeZone = substr($dateTime->getTimezone()->getName(), 0, 3);
     if (!in_array($timeZone, array('Etc', 'UTC'))) {
         throw new NotImplementedException('Time zone different than GMT or UTC is not supported as a formatting output.');
     }
     return $dateTime->format('\\G\\M\\TP');
 }
 /**
  * Formats DateTime object via Yii::$app->formatter
  * @param \DateTime $dateTime
  * @return string
  */
 private function format($dateTime)
 {
     $oldTimeZone = \Yii::$app->formatter->timeZone;
     \Yii::$app->formatter->timeZone = $dateTime->getTimezone()->getName();
     $result = \Yii::$app->formatter->asDatetime($dateTime);
     \Yii::$app->formatter->timeZone = $oldTimeZone;
     return $result;
 }
 /**
  * @param \DateTime $date
  *
  * @return array
  */
 public function formatDatetime($date)
 {
     if ($date) {
         $value = array('date' => $date->format('c'), 'timestamp' => $date->getTimestamp(), 'timezone' => $date->getTimezone()->getName());
         return $value;
     }
     return null;
 }
 /**
  * @param \DateTime $date
  * @param \DateTimeZone $timeZone
  */
 function it_records_chain_calls($date, $timeZone)
 {
     $date->getTimezone()->willReturn($timeZone)->shouldBeCalled();
     $timeZone->getName()->willReturn('+03:00')->shouldBeCalled();
     $this->getTimezone()->getName()->shouldBePlayedAs($date, '+03:00');
     // It's still immutable.
     $this->shouldBeEmpty();
 }
Example #22
0
 /**
  * @param \DateTime $dateTime
  * @return LocalDate
  */
 public static function raw(\DateTime $dateTime)
 {
     $tz = $dateTime->getTimezone();
     // normalize input coming from Javascript or Java etc...
     if ($tz->getName() === 'Z') {
         $tz = new \DateTimeZone('Etc/UTC');
     }
     return new LocalDate($dateTime, $tz);
 }
Example #23
0
 public function testHasTimezone()
 {
     $this->if($asserter = new sut($generator = new asserter\generator()))->exception(function () use($asserter) {
         $asserter->hasSize(rand(0, PHP_INT_MAX));
     })->isInstanceOf('mageekguy\\atoum\\exceptions\\logic')->hasMessage('Instance of \\dateTime is undefined')->if($asserter->setWith($dateTime = new \DateTime('now', $timezone = new \DateTimezone('Europe/Paris'))))->then->exception(function () use(&$line, &$requiredTimezone, $asserter) {
         $line = __LINE__;
         $asserter->hasTimezone($requiredTimezone = new \DateTimezone('Europe/London'));
     })->isInstanceOf('mageekguy\\atoum\\asserter\\exception')->hasMessage(sprintf($generator->getLocale()->_('Timezone is %s instead of %s'), $timezone->getName(), $requiredTimezone->getName()))->object($asserter->hasTimezone($dateTime->getTimezone()))->isIdenticalTo($asserter);
 }
Example #24
0
 /**
  * {@inheritdoc}
  *
  * @throws NotImplementedException When time zone is different than UTC or GMT (Etc/GMT)
  */
 public function format(\DateTime $dateTime, $length)
 {
     $timeZone = substr($dateTime->getTimezone()->getName(), 0, 3);
     if (!in_array($timeZone, array('Etc', 'UTC', 'GMT'))) {
         throw new NotImplementedException('Time zone different than GMT or UTC is not supported as a formatting output.');
     }
     // From ICU >= 4.8, the zero offset is not more used, example: GMT instead of GMT+00:00
     $format = 0 !== (int) $dateTime->format('O') ? '\\G\\M\\TP' : '\\G\\M\\T';
     return $dateTime->format($format);
 }
 public function getEndAtInTimezone()
 {
     if ($this->end_at->getTimezone() == $this->timezone) {
         return $this->end_at;
     } else {
         $ea = clone $this->end_at;
         $ea->setTimezone(new \DateTimeZone($this->timezone));
         return $ea;
     }
 }
Example #26
0
 /**
  * Converts a \DateTime object to MongoDB representation.
  * 
  * If <code>$value</code> is <i>NULL</i> (or not a \DateTime object), 
  * nothing is done and <i>NULL</i> returned.
  * 
  * @internal
  *      Resulting value is an array:
  *      <pre>
  *          array(
  *              'date' => \MongoDate(\DateTime::timestamp),
  *              'tz'   => TimeZone-Identifier (e.g. "Europe/Berlin")
  *          )
  *      </pre>
  *            
  * @param \DateTime|null $value
  * @return null|array
  * @see \Doctrine\ODM\MongoDB\Types\Type::convertToDatabaseValue()
  */
 public function convertToDatabaseValue($value)
 {
     if (!$value instanceof \DateTime) {
         return null;
     }
     $timezone = $value->getTimezone()->getName();
     $timestamp = $value->getTimestamp();
     $date = new \MongoDate($timestamp);
     return array('date' => $date, 'tz' => $timezone);
 }
 public function getEndAtInUTC()
 {
     if ($this->end_at->getTimezone() == 'UTC') {
         return $this->end_at;
     } else {
         $ea = clone $this->end_at;
         $ea->setTimezone(new \DateTimeZone("UTC"));
         return $ea;
     }
 }
Example #28
0
 /**
  *
  * @param int $weekDay ISO-8601 numeric representation of the day of the 
  *                     week (1 = Monday,..., 7 = Sunday)
  * @param \DateTime $month Any date within the desired month
  * @return \DateTime
  */
 public static function getFirstWeekday($weekDay, \DateTime $month)
 {
     $firstOfMonth = new \DateTime($month->format("Y-m-01 00:00:00"), $month->getTimezone());
     $firstOfMonthWeekday = intval($firstOfMonth->format("N"));
     $dayOfFirstWeekday = 1 + ($weekDay < $firstOfMonthWeekday ? 7 : 0) + $weekDay - $firstOfMonthWeekday;
     $firstWeekdayOfMonth = clone $firstOfMonth;
     $firstWeekdayOfMonth->setTime(0, 0, 0);
     $firstWeekdayOfMonth->add(new \DateInterval("P" . ($dayOfFirstWeekday - 1) . "D"));
     return $firstWeekdayOfMonth;
 }
Example #29
0
 public function testHasTimezone()
 {
     $this->given($asserter = $this->newTestedInstance->setLocale($locale = new \mock\atoum\locale()))->then->exception(function () use($asserter) {
         $asserter->hasTimezone(new \DateTimezone('Europe/London'));
     })->isInstanceOf('mageekguy\\atoum\\exceptions\\logic')->hasMessage('Instance of \\dateTime is undefined')->if($asserter->setWith($dateTime = new \DateTime('now', $timezone = new \DateTimezone('Europe/Paris'))))->then->object($asserter->hasTimezone($dateTime->getTimezone()))->isIdenticalTo($asserter)->if($this->calling($locale)->_ = $badTimezone = uniqid())->then->exception(function () use($asserter) {
         $asserter->hasTimezone(new \DateTimezone('Europe/London'));
     })->isInstanceOf('mageekguy\\atoum\\asserter\\exception')->hasMessage($badTimezone)->mock($locale)->call('_')->withArguments('Timezone is %s instead of %s', 'Europe/Paris', 'Europe/London')->once->exception(function () use($asserter, &$failMessage) {
         $asserter->hasTimezone(new \DateTimezone('Europe/London'), $failMessage = uniqid());
     })->isInstanceOf('mageekguy\\atoum\\asserter\\exception')->hasMessage($failMessage);
 }
Example #30
0
	public function getFormatted($format, $desttimezone = Time::TIMEZONE_USER){
		if($format == 'RELATIVE'){
			//return Time::GetRelativeAsString($date, Time::TIMEZONE_USER);
			return $this->getRelative();
		}
		else{
			// Check the offsets.  If they're the same, no change really needed.
			$tzto = self::_GetTimezone($desttimezone);

			if($tzto->getName() == $this->_dt->getTimezone()->getName()){
				return $this->_dt->format($format);
			}
			// Else, I need to clone the object so I can change the timezone, then return that formatted.
			// In this case, changing the timezone will handle all translation operations internally :)
			$clone = clone $this->_dt;
			$clone->setTimezone($tzto);
			return $clone->format($format);
		}
	}