DateTimeZone PHP Class Code Examples

This page contains top rated real world PHP examples of class DateTimeZone extracted from open source projects. You can rate examples to help us improve the quality of examples

Example #1
Show file File: DateTimeField.php Project: Bergdahls/YetiForceCRM
0
 /**
  *
  * @param type $time
  * @param type $sourceTimeZoneName
  * @param type $targetTimeZoneName
  * @return DateTime
  */
 public static function convertTimeZone($time, $sourceTimeZoneName, $targetTimeZoneName)
 {
     $log = vglobal('log');
     $log->debug('Start ' . __CLASS__ . ':' . __FUNCTION__ . "({$time}, {$sourceTimeZoneName}, {$targetTimeZoneName})");
     // TODO Caching is causing problem in getting the right date time format in Calendar module.
     // Need to figure out the root cause for the problem. Till then, disabling caching.
     //if(empty(self::$cache[$time][$targetTimeZoneName])) {
     // create datetime object for given time in source timezone
     $sourceTimeZone = new DateTimeZone($sourceTimeZoneName);
     if ($time == '24:00') {
         $time = '00:00';
     }
     $current_user = vglobal('current_user');
     $format = $current_user->date_format;
     if (empty($format)) {
         $format = 'yyyy-mm-dd';
     }
     $time = str_replace(".", "-", $time);
     $time = str_replace("/", "-", $time);
     $myDateTime = new DateTime($time, $sourceTimeZone);
     // convert this to target timezone using the DateTimeZone object
     $targetTimeZone = new DateTimeZone($targetTimeZoneName);
     $myDateTime->setTimeZone($targetTimeZone);
     self::$cache[$time][$targetTimeZoneName] = $myDateTime;
     //}
     $myDateTime = self::$cache[$time][$targetTimeZoneName];
     $log->debug('End ' . __CLASS__ . ':' . __FUNCTION__);
     return $myDateTime;
 }
Example #2
Show file File: acf-timezone_picker-v4.php Project: Ricardo-Diaz/acf-timezone-picker
0
 function create_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'];
         ?>
             <option value="<?php 
         echo trim($tz);
         ?>
?php 
         echo trim($tz) == trim($field["value"]) ? 'selected="selected"' : '';
         ?>
php 
         echo $tz . ' (' . $abbr . ')';
         ?>
ption>
         <?php 
     }
     ?>
     </select>
 <?php 
 }
Example #3
Show file File: agenda.lib.php Project: omaoibrahim/chamilo-lms
0
 /**
  * Format needed for the Fullcalendar js lib
  *
  * @param string $utcTime
  * @return bool|string
  */
 private function formatEventDate($utcTime)
 {
     $utcTimeZone = new DateTimeZone('UTC');
     $platformTimeZone = new DateTimeZone(_api_get_timezone());
     $eventDate = new DateTime($utcTime, $utcTimeZone);
     $eventDate->setTimezone($platformTimeZone);
     return $eventDate->format(DateTime::ISO8601);
 }
Example #4
Show file File: CXDSTools.class.php Project: fbone/mediboard4
0
 /**
  * Retourne le datetime actuelle au format UTC
  *
  * @param String $date now
  *
  * @return string
  */
 static function getTimeUtc($date = "now")
 {
     $timezone_local = new DateTimeZone(CAppUI::conf("timezone"));
     $timezone_utc = new DateTimeZone("UTC");
     $date = new DateTime($date, $timezone_local);
     $date->setTimezone($timezone_utc);
     return $date->format("YmdHis");
 }
Example #5
Show file File: CHL7v3EventPRPA.class.php Project: fbone/mediboard4
0
 /**
  * Transforme une chaine date au format time CDA
  *
  * @param String $dateTime String
  *
  * @return string
  */
 function setUtcToTime($dateTime)
 {
     $timezone_local = new DateTimeZone(CAppUI::conf("timezone"));
     $timezone_utc = new DateTimeZone("UTC");
     $date = new DateTime($dateTime, $timezone_utc);
     $date->setTimezone($timezone_local);
     return $date->format("d-m-Y H:i");
 }
Example #6
Show file File: AppController.php Project: anillaogi016/demo_o
0
 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);
 }
Example #7
Show file File: AbstractModel.php Project: railto/joindin-api
0
 /**
  * Return this object with client-facing fields and hypermedia, ready for output
  */
 public function getOutputView(Request $request, $verbose = false)
 {
     $item = array();
     if ($verbose) {
         $fields = $this->getVerboseFields();
     } else {
         $fields = $this->getDefaultFields();
     }
     $fields = array_merge($fields, $this->getSubResources());
     // special handling for dates
     if ($this->event_tz_place != '' && $this->event_tz_cont != '') {
         $tz = new DateTimeZone($this->event_tz_cont . '/' . $this->event_tz_place);
     } else {
         $tz = new DateTimeZone('UTC');
     }
     foreach ($fields as $output_name => $name) {
         $value = $this->{$name};
         // override if it is a date
         if (substr($output_name, -5) == '_date' && !empty($value)) {
             $value = (new DateTime('@' . $value))->setTimezone($tz)->format('c');
         }
         $item[$output_name] = $value;
     }
     return $item;
 }
Example #8
Show file File: ApiMapper.php Project: railto/joindin-api
0
 public function transformResults($results, $verbose)
 {
     $fields = $verbose ? $this->getVerboseFields() : $this->getDefaultFields();
     $retval = array();
     // format results to only include named fields
     foreach ($results as $row) {
         $entry = array();
         foreach ($fields as $key => $value) {
             // special handling for dates
             if (substr($key, -5) == '_date' && !empty($row[$value])) {
                 if ($row['event_tz_place'] != '' && $row['event_tz_cont'] != '') {
                     $tz = new DateTimeZone($row['event_tz_cont'] . '/' . $row['event_tz_place']);
                 } else {
                     $tz = new DateTimeZone('UTC');
                 }
                 $entry[$key] = (new DateTime('@' . $row[$value]))->setTimezone($tz)->format('c');
             } else {
                 if (array_key_exists($value, $row)) {
                     $entry[$key] = $row[$value];
                 } else {
                     $entry[$key] = null;
                 }
             }
         }
         $retval[] = $entry;
     }
     return $retval;
 }
Example #9
Show file File: date.php Project: Simarpreet05/joomla
0
 /**
  * Constructor.
  *
  * @param   string  $date  String in a format accepted by strtotime(), defaults to "now".
  * @param   mixed   $tz    Time zone to be used for the date.
  *
  * @return  void
  * @since   11.1
  *
  * @throws  JException
  */
 public function __construct($date = 'now', $tz = null)
 {
     // Create the base GMT and server time zone objects.
     if (empty(self::$gmt) || empty(self::$stz)) {
         self::$gmt = new DateTimeZone('GMT');
         self::$stz = new DateTimeZone(@date_default_timezone_get());
     }
     // If the time zone object is not set, attempt to build it.
     if (!$tz instanceof DateTimeZone) {
         if ($tz === null) {
             $tz = self::$gmt;
         } elseif (is_numeric($tz)) {
             // Translate from offset.
             $tz = new DateTimeZone(self::$offsets[(string) $tz]);
         } elseif (is_string($tz)) {
             $tz = new DateTimeZone($tz);
         }
     }
     // If the date is numeric assume a unix timestamp and convert it.
     date_default_timezone_set('UTC');
     $date = is_numeric($date) ? date('c', $date) : $date;
     // Call the DateTime constructor.
     parent::__construct($date, $tz);
     // reset the timezone for 3rd party libraries/extension that does not use JDate
     date_default_timezone_set(self::$stz->getName());
     // Set the timezone object for access later.
     $this->_tz = $tz;
 }
Example #10
Show file File: server.php Project: Gritch69/XG-Project
0
 /**
  * method time_zone_picker
  * param
  * return return the select options
  */
 private function time_zone_picker()
 {
     $utc = new DateTimeZone('UTC');
     $dt = new DateTime('now', $utc);
     $time_zones = '';
     $current_time_zone = Functions_Lib::read_config('date_time_zone');
     // Get the data
     foreach (DateTimeZone::listIdentifiers() as $tz) {
         $current_tz = new DateTimeZone($tz);
         $offset = $current_tz->getOffset($dt);
         $transition = $current_tz->getTransitions($dt->getTimestamp(), $dt->getTimestamp());
         foreach ($transition as $element => $data) {
             $time_zones_data[$data['offset']][] = $tz;
         }
     }
     // Sort by key
     ksort($time_zones_data);
     // Build the combo
     foreach ($time_zones_data as $offset => $tz) {
         $time_zones .= '<optgroup label="GMT' . $this->format_offset($offset) . '">';
         foreach ($tz as $key => $zone) {
             $time_zones .= '<option value="' . $zone . '" ' . ($current_time_zone == $zone ? ' selected' : '') . ' >' . $zone . '</option>';
         }
         $time_zones .= '</optgroup>';
     }
     // Return data
     return $time_zones;
 }
Example #11
Show file File: acf-timezone_picker-v5.php Project: Ricardo-Diaz/acf-timezone-picker
0
 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 . ')';
         ?>
ption>
         <?php 
     }
     ?>
     </select>
 <?php 
 }
Example #12
Show file File: ObjectsTest.php Project: jasonsoso/custom-templates
0
 public function testIsDate()
 {
     // from js
     $this->assertFalse(__::isDate(1), 'numbers are not dates');
     $this->assertFalse(__::isDate(new StdClass()), 'objects are not dates');
     if (class_exists('DateTime')) {
         $timezone = new DateTimeZone('America/Denver');
         $this->assertTrue(__::isDate(new DateTime(null, $timezone)), 'but dates are');
     }
     // extra
     $this->assertFalse(__::isDate(time()), 'timestamps are not dates');
     $this->assertFalse(__::isDate('Y-m-d H:i:s'), 'date strings are not dates');
     $this->assertFalse(__(time())->isDate());
     if (class_exists('DateTime')) {
         $timezone = new DateTimeZone('America/Denver');
         $this->assertTrue(__(new DateTime(null, $timezone))->isDate(), 'dates are dates with OO-style call');
     }
     // docs
     $this->assertFalse(__::isDate(null));
     $this->assertFalse(__::isDate('2011-06-09 01:02:03'));
     if (class_exists('DateTime')) {
         $timezone = new DateTimeZone('America/Denver');
         $this->assertTrue(__::isDate(new DateTime(null, $timezone)));
     }
 }
Example #13
Show file File: index.php Project: abouthalf/archies-recipes
0
/**
 * Return RSS formatted date constructed from timestamp in blog file name
 *
 * @param string $name
 * @param Application $app
 * @return string formatted date string
 */
function buildPubDateFromFileName($name, $app)
{
    $datePattern = '/^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d) (.*)\\.html$/';
    $dateTimePattern = '/^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d)-(\\d\\d)-(\\d\\d) (.*).html$/';
    $tz = new DateTimeZone($app['timezone']);
    $gmt = new DateTimeZone('GMT');
    $stamp = '%s-%s-%s %s:%s:%s';
    $year = date('Y');
    $month = date('m');
    $day = date('d');
    $hour = '12';
    // noon is a good default hour
    $minute = '00';
    $second = '00';
    if (preg_match($datePattern, $name, $matches)) {
        $year = $matches[1];
        $month = $matches[2];
        $day = $matches[3];
    } elseif (preg_match($dateTimePattern, $name, $matches)) {
        $year = $matches[1];
        $month = $matches[2];
        $day = $matches[3];
        $hour = $matches[4];
        $minute = $matches[5];
        $second = $matches[6];
    }
    $date = new DateTime(sprintf($stamp, $year, $month, $day, $hour, $minute, $second), $tz);
    // set to GMT timezone
    $date->setTimezone($gmt);
    return $date->format(DATE_RSS);
}
Example #14
Show file File: ShowInstance.php Project: RadioCampusFrance/airtime
0
 public function getShowListContent()
 {
     $con = Propel::getConnection();
     $sql = <<<SQL
ECT *
M (
     (SELECT s.starts,
             0::INTEGER as type ,
             f.id           AS item_id,
             f.track_title,
             f.album_title  AS album,
             f.genre        AS genre,
             f.length       AS length,
             f.artist_name  AS creator,
             f.file_exists  AS EXISTS,
             f.filepath     AS filepath,
             f.mime         AS mime
      FROM cc_schedule AS s
      LEFT JOIN cc_files AS f ON f.id = s.file_id
      WHERE s.instance_id = :instance_id1
        AND s.playout_status >= 0
        AND s.file_id IS NOT NULL
        AND f.hidden = 'false')
   UNION
     (SELECT s.starts,
             1::INTEGER as type,
             ws.id AS item_id,
             (ws.name || ': ' || ws.url) AS title,
             null            AS album,
             null            AS genre,
             ws.length       AS length,
             sub.login       AS creator,
             't'::boolean    AS EXISTS,
             ws.url          AS filepath,
             ws.mime as mime
      FROM cc_schedule AS s
      LEFT JOIN cc_webstream AS ws ON ws.id = s.stream_id
      LEFT JOIN cc_subjs AS sub ON ws.creator_id = sub.id
      WHERE s.instance_id = :instance_id2
        AND s.playout_status >= 0
        AND s.stream_id IS NOT NULL)) AS temp
ER BY starts;
;
     $stmt = $con->prepare($sql);
     $stmt->execute(array(':instance_id1' => $this->_instanceId, ':instance_id2' => $this->_instanceId));
     $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
     $userTimezone = Application_Model_Preference::GetUserTimezone();
     $displayTimezone = new DateTimeZone($userTimezone);
     $utcTimezone = new DateTimeZone("UTC");
     foreach ($results as &$row) {
         $dt = new DateTime($row["starts"], $utcTimezone);
         $dt->setTimezone($displayTimezone);
         $row["starts"] = $dt->format("Y-m-d H:i:s");
         if (isset($row['length'])) {
             $formatter = new LengthFormatter($row["length"]);
             $row["length"] = $formatter->format();
         }
     }
     return $results;
 }
Example #15
Show file File: sp-db-statistics.php Project: brooklyntri/btc-plugins
0
function sp_set_last_visited($userid)
{
    global $spThisUser;
    # before setting last visit check and save timezone difference just to be sure.
    $opts = sp_get_member_item($userid, 'user_options');
    if (!empty($opts['timezone_string'])) {
        if (preg_match('/^UTC[ \\t+-]/', $opts['timezone_string'])) {
            # correct for manual UTC offets
            $userOffset = preg_replace('/UTC\\+?/', '', $opts['timezone_string']) * 3600;
        } else {
            # get timezone offset for user
            $date_time_zone_selected = new DateTimeZone(sp_esc_str($opts['timezone_string']));
            $userOffset = timezone_offset_get($date_time_zone_selected, date_create());
        }
        $wptz = get_option('timezone_string');
        if (empty($wptz)) {
            $serverOffset = get_option('gmt_offset');
        } else {
            $date_time_zone_selected = new DateTimeZone($wptz);
            $serverOffset = timezone_offset_get($date_time_zone_selected, date_create());
        }
        # calculate time offset between user and server
        $ntz = (int) round(($userOffset - $serverOffset) / 3600, 2);
        if ($opts['timezone'] != $ntz) {
            $opts['timezone'] = $ntz;
            $spThisUser->timezone = $ntz;
            sp_update_member_item($userid, 'user_options', $opts);
            sp_update_member_item($userid, 'checktime', 0);
        }
    }
    # Now set the last visit date/time
    sp_update_member_item($userid, 'lastvisit', 0);
}
Example #16
Show file File: owncloud.php Project: omusico/isle-web-framework
0
 /**
  * write a message in the log
  * @param string $app
  * @param string $message
  * @param int $level
  */
 public static function write($app, $message, $level)
 {
     $minLevel = min(OC_Config::getValue("loglevel", OC_Log::WARN), OC_Log::ERROR);
     if ($level >= $minLevel) {
         // default to ISO8601
         $format = OC_Config::getValue('logdateformat', 'c');
         $logtimezone = OC_Config::getValue("logtimezone", 'UTC');
         try {
             $timezone = new DateTimeZone($logtimezone);
         } catch (Exception $e) {
             $timezone = new DateTimeZone('UTC');
         }
         $time = new DateTime(null, $timezone);
         // remove username/passswords from URLs before writing the to the log file
         $message = preg_replace('/\\/\\/(.*):(.*)@/', '//xxx:xxx@', $message);
         $entry = array('app' => $app, 'message' => $message, 'level' => $level, 'time' => $time->format($format));
         $entry = json_encode($entry);
         $handle = @fopen(self::$logFile, 'a');
         @chmod(self::$logFile, 0640);
         if ($handle) {
             fwrite($handle, $entry . "\n");
             fclose($handle);
         } else {
             // Fall back to error_log
             error_log($entry);
         }
     }
 }
Example #17
Show file File: DateTime_extends_basic2.php Project: badlamer/hhvm
0
 public function __construct($date = null, DateTimeZone $dtz = null)
 {
     if ($dtz === null) {
         $dtz = new DateTimeZone(date_default_timezone_get());
     }
     parent::__construct($date, $dtz);
 }
Example #18
Show file File: EEM_Payment.model.php Project: DavidSteinbauer/event-espresso-core
0
 /**
  * retrieve  all payments from db between two dates,
  *
  * @param string $start_date incoming start date. If empty the beginning of today is used.
  * @param string $end_date   incoming end date. If empty the end of today is used.
  * @param string $format  	If you include $start_date or $end_date then you must include the format string
  *                         		for the format your date is in.
  * @param string $timezone   If your range is in a different timezone then the current setting on this
  *                           		WordPress install, then include it here.
  * @throws EE_Error
  *
  * @return EE_Payment[]
  */
 public function get_payments_made_between_dates($start_date = '', $end_date = '', $format = '', $timezone = '')
 {
     EE_Registry::instance()->load_helper('DTT_Helper');
     $timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
     //if $start_date or $end date, verify $format is included.
     if ((!empty($start_date) || !empty($end_date)) && empty($format)) {
         throw new EE_Error(__('You included a start date and/or a end date for this method but did not include a format string.  The format string is needed for setting up the query', 'event_espresso'));
     }
     $now = new DateTime('now');
     // setup timezone objects once
     $modelDateTimeZone = new DateTimeZone($this->_timezone);
     $passedDateTimeZone = new DateTimeZone($timezone);
     // setup start date
     $start_date = !empty($start_date) ? date_create_from_format($format, $start_date, $passedDateTimeZone) : $now;
     $start_date->setTimeZone($modelDateTimeZone);
     $start_date = $start_date->format('Y-m-d') . ' 00:00:00';
     $start_date = strtotime($start_date);
     // setup end date
     $end_date = !empty($end_date) ? date_create_from_format($format, $end_date, $passedDateTimeZone) : $now;
     $end_date->setTimeZone($modelDateTimeZone);
     $end_date = $end_date->format('Y-m-d') . ' 23:59:59';
     $end_date = strtotime($end_date);
     // make sure our start date is the lowest value and vice versa
     $start = min($start_date, $end_date);
     $end = max($start_date, $end_date);
     //yes we generated the date and time string in utc but we WANT this start date and time used in the set timezone on the model.
     $start_date = $this->convert_datetime_for_query('PAY_timestamp', date('Y-m-d', $start) . ' 00:00:00', 'Y-m-d H:i:s', $this->get_timezone());
     $end_date = $this->convert_datetime_for_query('PAY_timestamp', date('Y-m-d', $end) . ' 23:59:59', 'Y-m-d H:i:s', $this->get_timezone());
     return $this->get_all(array(array('PAY_timestamp' => array('>=', $start_date), 'PAY_timestamp*' => array('<=', $end_date))));
 }
Example #19
Show file File: TimeZoneTest.php Project: youprofit/Zurmo
0
 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 #20
Show file File: ZurmoTimeZoneHelper.php Project: RamaKavanan/InitialVersion
0
 /**
  * Gets timezone offset.
  * @return int in seconds
  */
 public static function getTimeZoneOffset()
 {
     $userTimeZone = new DateTimeZone(Yii::app()->timeZoneHelper->getForCurrentUser());
     $gmtTimeZone = new DateTimeZone('GMT');
     $dateTimeUser = new DateTime("now", $gmtTimeZone);
     return $userTimeZone->getOffset($dateTimeUser);
 }
Example #21
Show file File: Weights.php Project: yisrael1981/weight
0
 public function GET()
 {
     $policy = new Policy_LoggedIn($this->app);
     $app = Config::get('app');
     $userid = $policy->getData();
     $request = $this->app->request();
     if (!$userid) {
         throw new Exception_Api("Unable to authenticate.");
     }
     $days_back = trim($request->get('days_back'));
     if (!is_numeric($days_back) && $days_back != 'all' && $days_back != 'ytd') {
         throw new Exception_Api('Missing or invalid days_back field.');
     }
     $mapper = new Mapper_Settings();
     $mapper->updateSettingForUserid($userid, 'default_view', $days_back);
     $settings = $mapper->getFilteredSettingsByUserid($userid);
     $serverDateTimeZone = new DateTimeZone($app->default_timezone);
     $userDateTimeZone = new DateTimeZone($settings['timezone']);
     $serverDateTime = new DateTime("now", $serverDateTimeZone);
     $userDateTime = new DateTime("now", $userDateTimeZone);
     $tzDiff = $userDateTime->getOffset() - $serverDateTime->getOffset();
     $tzDiff = $tzDiff / (60 * 60);
     $weight_mapper = new Mapper_Weight();
     $weights = $weight_mapper->getWeightsForUser($userid, $days_back);
     $formatted_weights = array();
     foreach ($weights as $weight) {
         $formatted_weights[] = array('date' => $weight['create_time'], 'weight' => $weight['weight'], 'comment' => htmlentities($weight['comment']));
     }
     return array('data' => $formatted_weights, 'units' => $app->weight_units, 'tz_offset' => $tzDiff);
 }
Example #22
Show file File: functions.php Project: pemiu01/exchange-addon-licensing
0
/**
 * Convert a GMT date to its localized equivalent.
 *
 * @internal
 *
 * @since 1.0
 *
 * @param \DateTime $time
 *
 * @return \DateTime
 */
function convert_gmt_to_local(\DateTime $time)
{
    if ($time->getOffset() != 0) {
        throw new \InvalidArgumentException("Passed DateTime object is not in GMT time.");
    }
    $tz_string = get_option('timezone_string');
    if (!empty($tz_string)) {
        $tz = new \DateTimeZone($tz_string);
        $time->setTimezone($tz);
        return $time;
    } else {
        $tz = new \DateTimeZone('UTC');
        $time->setTimezone($tz);
        $offset = get_option('gmt_offset', 0);
        if ($offset == 0) {
            return $time;
        }
        $invert = $offset < 0;
        $parts = explode('.', $offset);
        $hours = $parts[0];
        $interval_spec = "PT{$hours}H";
        if (isset($parts[1])) {
            $minutes_fraction = (double) "0.{$parts['1']}";
            $minutes = 60 * $minutes_fraction;
            if ($minutes) {
                $interval_spec .= "{$minutes}M";
            }
        }
        $interval = new \DateInterval($interval_spec);
        $interval->invert = $invert;
        $time->add($interval);
        return $time;
    }
}
Example #23
Show file File: TimezoneHelper.php Project: christine-ho-dev/movim
0
function generateTimezoneList()
{
    $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);
        $utc = new DateTimeZone('UTC');
        $timezone_offsets[$timezone] = $tz->getOffset(new DateTime('now', $utc));
    }
    // 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}";
        $split = explode("/", $timezone);
        $timezone_list[$timezone] = "{$split['1']}/{$split['0']} ({$pretty_offset})";
    }
    asort($timezone_list);
    return $timezone_list;
}
Example #24
Show file File: date.class.php Project: spacequad/glfusion
0
 /**
  * Constructor.
  *
  * @param   string  String in a format accepted by strtotime(), defaults to "now".
  * @param   mixed   Time zone to be used for the date.
  * @return  void
  *
  */
 public function __construct($date = 'now', $tz = null)
 {
     // Create a base GMT and a server time zone object
     if (empty(self::$gmt) || empty(self::$stz)) {
         self::$gmt = new DateTimeZone('GMT');
         self::$stz = new DateTimeZone(@date_default_timezone_get());
     }
     // validate we have a good timezone
     if (@date_default_timezone_set($tz) == FALSE) {
         $tz = self::$gmt;
     }
     // If the time zone object is not set, attempt to build it.
     if (!$tz instanceof DateTimeZone) {
         if ($tz === null) {
             $tz = self::$gmt;
         } elseif (is_numeric($tz)) {
             // Translate from offset.
             $tz = new DateTimeZone(self::$offsets[(string) $tz]);
         } elseif (is_string($tz)) {
             $tz = new DateTimeZone($tz);
         }
     }
     // If the date is numeric assume a unix timestamp and convert it.
     date_default_timezone_set('UTC');
     $date = is_numeric($date) ? date('c', $date) : $date;
     // Call the DateTime constructor.
     parent::__construct($date, $tz);
     // Set the timezone object for access later.
     $this->_tz = $tz;
 }
Example #25
Show file File: DateHelper.php Project: RadioCampusFrance/airtime
0
 public static function UserTimezoneStringToUTCString($datetime, $format = "Y-m-d H:i:s")
 {
     $userTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
     $utcTimezone = new DateTimeZone("UTC");
     $d = new DateTime($datetime, $userTimezone);
     $d->setTimezone($utcTimezone);
     return $d->format($format);
 }