Example #1
0
 public function getDateDelta($date)
 {
     $date = new DateTime($date);
     $diff = abs(time() - $date->getTimestamp());
     if ($diff < 10) {
         $message = "à l'instant";
     } else {
         if ($diff < 30) {
             $message = "il y a quelques secondes";
         } else {
             if ($diff < 60) {
                 $message = "il y a moins d'une minute";
             } else {
                 if (ceil($diff / 60) < 60) {
                     $message = "il y a " . ceil($diff / 60) . " minutes";
                 } else {
                     if (ceil($diff / 60 / 60) == 1) {
                         $message = "il y a environ une heure";
                     } else {
                         if (ceil($diff / 60 / 60) < 24) {
                             $message = "il y a " . ceil($diff / 60 / 60) . " heures";
                         } else {
                             // version linux :
                             // setlocale(LC_TIME, 'fr', 'fr_FR', 'fr_FR.ISO8859-1');
                             // version windows
                             setlocale(LC_TIME, 'french');
                             $message = utf8_encode(strftime('%#d %B, %H:%M', $date->getTimestamp()));
                         }
                     }
                 }
             }
         }
     }
     return $message;
 }
 public function getParams()
 {
     $params = [];
     empty($this->dateMin) ?: ($params['date_min'] = $this->dateMin->getTimestamp());
     empty($this->dateMax) ?: ($params['date_max'] = $this->dateMax->getTimestamp());
     return $params;
 }
 /**
  * Check if the user has a valid reset password token.
  *
  * @return bool
  */
 public function hasValidResetPasswordToken()
 {
     if ($this->resetPasswordTokenValidUntil == null) {
         return false;
     }
     return $this->resetPasswordTokenValidUntil->getTimestamp() > time();
 }
Example #4
0
 public function testFormatTime()
 {
     $this->assertEquals($this->_dateTime->format(self::TIME_FORMAT_SHORT), $this->_helper->formatTime());
     $this->assertEquals($this->_dateTime->format(self::DATETIME_FORMAT_SHORT), $this->_helper->formatTime(null, 'short', true));
     $zendDate = new Zend_Date($this->_dateTime->getTimestamp());
     $this->assertEquals($zendDate->toString(self::TIME_FORMAT_SHORT_ISO), $this->_helper->formatTime($zendDate, 'short'));
 }
Example #5
0
function file_load($type = 'metar')
{
    $remote_file = 'http://weather.aero/dataserver1_5/cache/' . $type . 's.cache.xml.gz';
    $local_file = $type . '.xml';
    $dt = NULL;
    if (file_exists($local_file)) {
        $h = get_headers($remote_file, 1);
        if (!(strstr($h[0], '200') === FALSE)) {
            $dt = new \DateTime($h['Last-Modified']);
            if ($dt->getTimestamp() - filemtime($local_file) < 300) {
                echo "Remote : " . $dt->getTimestamp() . " VS Local: " . filemtime($local_file) . " = " . ($dt->getTimestamp() - filemtime($local_file)) . "<br>";
                $xml = simplexml_load_file($local_file);
            } else {
                echo "Updating local file";
                $data = file_get_contents('compress.zlib://' . $remote_file);
                if (file_put_contents($local_file, $data)) {
                    $xml = simplexml_load_file($local_file);
                }
            }
            //echo "R - ".$dt->getTimestamp()." - "
            //.$dt->format('F d Y H:i:s')."<br/>";
        }
    } else {
        $data = file_get_contents('compress.zlib://' . $remote_file);
        if (file_put_contents($local_file, $data)) {
            $xml = simplexml_load_file($local_file);
        }
    }
    return $xml;
}
 public function test_StoreAnomaly_RetrieveGroupedAndSortedByNofAnomalies()
 {
     /* This tries to test something that's a bit difficult to test.
      * The anomalies should be retrieved in sorted order from highest number of anomalies to lowest,
      * and contain all the anomalies for each group.
      *
      * We don't test limit and minCount here
      */
     $start = new DateTime('-5 minutes');
     $end = new DateTime('now');
     // Group 1
     $this->conn->col('anomalies')->insert(['nid' => '1', 'sid' => '1', 'predicted' => 30, 'actual' => 70, 'mongodate' => new MongoDate($start->getTimestamp())]);
     $this->conn->col('anomalies')->insert(['nid' => '1', 'sid' => '1', 'predicted' => 40, 'actual' => 80, 'mongodate' => new MongoDate($end->getTimestamp())]);
     $this->conn->col('anomalies')->insert(['nid' => '1', 'sid' => '1', 'predicted' => 45, 'actual' => 85, 'mongodate' => new MongoDate($end->getTimestamp())]);
     // Group 2
     $this->conn->col('anomalies')->insert(['nid' => '2', 'sid' => '1', 'predicted' => 50, 'actual' => 90, 'mongodate' => new MongoDate($start->getTimestamp())]);
     // Group 3
     $this->conn->col('anomalies')->insert(['nid' => '2', 'sid' => '2', 'predicted' => 60, 'actual' => 100, 'mongodate' => new MongoDate($start->getTimestamp())]);
     $this->conn->col('anomalies')->insert(['nid' => '2', 'sid' => '2', 'predicted' => 60, 'actual' => 100, 'mongodate' => new MongoDate($end->getTimestamp())]);
     $pipeline = new Pipeline();
     $pipelineFactory = new Factory($this->conn);
     $sequence = $pipelineFactory->createAnomalyAction($start, $end, ['1', '2'], ['1', '2'], 1, 3);
     $res = $pipeline->run($sequence);
     $this->assertEquals(3, count($res), 'Expected number of groups were wrong');
     $this->assertEquals(3, count($res[0]['anomalies']), 'Expected number of anomalies in grp1 were wrong');
     $this->assertEquals(2, count($res[1]['anomalies']), 'Expected number of anomalies in grp3 were wrong');
     $this->assertEquals(1, count($res[2]['anomalies']), 'Expected number of anomalies in grp2 were wrong');
 }
    function render_field($field)
    {
        /*
         *  Create a select dropdown with all available timezones
         */
        $utc = new DateTimeZone('UTC');
        $dt = new DateTime('now', $utc);
        ?>
        <select name="<?php 
        echo esc_attr($field['name']);
        ?>
">
            <?php 
        foreach (\DateTimeZone::listIdentifiers() as $tz) {
            $current_tz = new \DateTimeZone($tz);
            $transition = $current_tz->getTransitions($dt->getTimestamp(), $dt->getTimestamp());
            $abbr = $transition[0]['abbr'];
            $is_selected = trim($field['value']) === trim($tz) ? ' selected="selected"' : '';
            ?>
                <option value="<?php 
            echo $tz;
            ?>
"<?php 
            echo $is_selected;
            ?>
><?php 
            echo $tz . ' (' . $abbr . ')';
            ?>
</option>
            <?php 
        }
        ?>
        </select>
    <?php 
    }
Example #8
0
 private function documentProcessing($feed, $count, $date)
 {
     $news = array();
     $idx = 0;
     foreach ($feed->channel->item as $new) {
         if ($idx < $count) {
             $pubDate = new DateTime($new->pubDate);
             if ($date && $pubDate->getTimestamp() <= $date) {
                 continue;
             }
             $doc = new DOMDocument();
             @$doc->loadHTML($new->description);
             //Obtenemos las imágenes contenidas en las descripción.
             $images = $doc->getElementsByTagName('img');
             if ($images->length > 0) {
                 $poster = array();
                 foreach ($images as $image) {
                     $alt = $image->getAttribute('alt');
                     $src = $image->getAttribute('src');
                     $title = $image->getAttribute('title');
                     array_push($poster, array("alt" => $alt, "src" => $src, "title" => $title));
                 }
                 array_push($news, array("posters" => $poster, "title" => $new->title, "link" => $new->link, "date" => $pubDate->getTimestamp(), "desc" => $new->description));
                 $idx++;
             }
         } else {
             break;
         }
     }
     return $news;
 }
Example #9
0
 public function getDateArray()
 {
     if ($this->dateTime->getTimestamp() < 0) {
         return [0, 0, 0];
     }
     return explode('-', $this->dateTime->format('Y-m-d'));
 }
 /**
  * A data provider for testFormat method.
  */
 public function formatProvider()
 {
     $now = new \DateTime();
     $format = "%H:%M %d-%m-%Y";
     $expected = strftime($format, $now->getTimestamp());
     return array(array($now, $format, $expected), array($now->getTimestamp(), $format, $expected), array((string) $now->getTimestamp(), $format, $expected));
 }
function getWeather($loc, $units = 'metric', $lang = 'en', $appid = '', $cachetime = 0)
{
    $url = "http://api.openweathermap.org/data/2.5/weather?q=" . $loc . "&appid=" . $appid . "&lang=" . $lang . "&units=" . $units . "&mode=xml";
    $cached = Cache::get('curweather' . md5($url));
    $now = new DateTime();
    if (!is_null($cached)) {
        $cdate = get_pconfig(local_user(), 'curweather', 'last');
        $cached = unserialize($cached);
        if ($cdate + $cachetime > $now->getTimestamp()) {
            return $cached;
        }
    }
    try {
        $res = new SimpleXMLElement(fetch_url($url));
    } catch (Exception $e) {
        info(t('Error fetching weather data.\\nError was: ' . $e->getMessage()));
        return false;
    }
    if ((string) $res->temperature['unit'] === 'metric') {
        $tunit = '°C';
        $wunit = 'm/s';
    } else {
        $tunit = '°F';
        $wunit = 'mph';
    }
    if (trim((string) $res->weather['value']) == trim((string) $res->clouds['name'])) {
        $desc = (string) $res->clouds['name'];
    } else {
        $desc = (string) $res->weather['value'] . ', ' . (string) $res->clouds['name'];
    }
    $r = array('city' => (string) $res->city['name'][0], 'country' => (string) $res->city->country[0], 'lat' => (string) $res->city->coord['lat'], 'lon' => (string) $res->city->coord['lon'], 'temperature' => (string) $res->temperature['value'][0] . $tunit, 'pressure' => (string) $res->pressure['value'] . (string) $res->pressure['unit'], 'humidity' => (string) $res->humidity['value'] . (string) $res->humidity['unit'], 'descripion' => $desc, 'wind' => (string) $res->wind->speed['name'] . ' (' . (string) $res->wind->speed['value'] . $wunit . ')', 'update' => (string) $res->lastupdate['value'], 'icon' => (string) $res->weather['icon']);
    set_pconfig(local_user(), 'curweather', 'last', $now->getTimestamp());
    Cache::set('curweather' . md5($url), serialize($r), CACHE_HOUR);
    return $r;
}
 /**
  * Gets the time difference, but always returns it in a certain format
  * @param string $format The format, could be one of these: 
  * 'seconds', 'minutes', 'hours', 'days', 'months', 'years'.
  * 
  * @return string
  */
 public function DiffIn($format = 'default')
 {
     if ($this->owner->value) {
         $now = new DateTime();
         $timestamp = strtotime($this->owner->value);
         $value = new DateTime('@' . $timestamp);
         $diff = $value->diff($now);
         switch ($format) {
             case "seconds":
                 return abs($value->getTimestamp() - $now->getTimestamp());
                 break;
             case "minutes":
                 return abs(round(($value->getTimestamp() - $now->getTimestamp()) / 60));
                 break;
             case "hours":
                 return abs(round(($value->getTimestamp() - $now->getTimestamp()) / 60 / 60));
                 break;
             case "days":
                 return abs(round(($value->getTimestamp() - $now->getTimestamp()) / 60 / 60 / 24));
                 break;
             case "months":
                 return $diff->format('%m') + $diff->format('%y') * 12;
                 break;
             case "years":
                 return $diff->format('%y');
                 break;
             default:
                 return $diff;
                 break;
         }
     }
 }
Example #13
0
 public function testSpecifiedTimeZone()
 {
     $util = new DateTimeUtil(new \DateTimeZone('Asia/Singapore'));
     $dateTime = $util->createDateTimeByUnixTime($this->timestamp->getTimestamp());
     $this->assertEquals($this->timestamp, $dateTime);
     $this->assertEquals('+0800', $dateTime->format('O'));
 }
Example #14
0
 /**
  * Check that today is between start & end
  * @return bool
  */
 public function isSumerSchedule()
 {
     $today = new \DateTime('today');
     $start = $this->getSumerScheduleStart();
     $end = $this->getSumerScheduleEnd();
     return $today->getTimestamp() >= $start->getTimestamp() && $today->getTimestamp() <= $end->getTimestamp();
 }
Example #15
0
 /**
  * @param Season $season
  * @return \AppBundle\Entity\Member[]
  */
 public function findNextBirthdays(Season $season)
 {
     // Period to scan
     $start = new \DateTime('-1 week');
     $stop = new \DateTime('+3 weeks');
     $builder = $this->createQueryBuilder('m')->innerJoin('m.memberships', 'ms')->andWhere('ms.season = :season')->setParameter('season', $season)->setParameter('start', $start->format('m-d'))->setParameter('stop', $stop->format('m-d'));
     if ($start->format('m') > $stop->format('m')) {
         $builder->andWhere('SUBSTRING( m.birthday, 6 ) >= :start OR SUBSTRING( m.birthday, 6 ) <= :stop');
     } else {
         $builder->andWhere('SUBSTRING( m.birthday, 6 ) BETWEEN :start AND :stop');
     }
     $members = $builder->getQuery()->getResult();
     // Sort by next birthday
     usort($members, function (Member $a, Member $b) use($stop) {
         $nextA = $a->getNextBirthday();
         $nextB = $b->getNextBirthday();
         if ($nextA->getTimestamp() > $stop->getTimestamp()) {
             $nextA->modify('-1 year');
         }
         if ($nextB->getTimestamp() > $stop->getTimestamp()) {
             $nextB->modify('-1 year');
         }
         return $nextA > $nextB;
     });
     return $members;
 }
 /**
  * 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);
 }
 /**
  * @return \DateTime|null
  */
 public function getDateTimeForRetry()
 {
     if ($this->retrySeconds === null) {
         return null;
     }
     return \DateTime::createFromFormat('U', $this->responseDateTime->getTimestamp())->modify('+' . $this->retrySeconds . ' seconds');
 }
 public static function ISSUEDATE()
 {
     $Date = new DateTime('now');
     $randomDate = mt_rand($Date->getTimestamp(), $Date->getTimestamp() + 15000000);
     $newRanDate = date("Y-m-d", $randomDate);
     return $newRanDate;
 }
 public function getParams()
 {
     $params = ['appid' => $this->appId, 'count' => $this->count, 'name' => $this->statNames];
     empty($this->startDate) ?: ($params['startdate'] = $this->startDate->getTimestamp());
     empty($this->endDate) ?: ($params['enddate'] = $this->endDate->getTimestamp());
     return $params;
 }
 /**
  * @param string $key
  * @param \DateTime $time
  *
  * @return bool
  */
 public function set($key, \DateTime $time)
 {
     $key = $this->prefix . $key;
     if (!($old_time = $this->memcache->get($key)) || $old_time < $time->getTimestamp()) {
         return $this->memcache->set($key, $time->getTimestamp());
     }
     return true;
 }
Example #21
0
 /**
  * @return string
  */
 public function __toString()
 {
     if ($this->date !== null) {
         return strftime('%a %d.%m.%Y %R', $this->date->getTimestamp());
     } else {
         return $this->text;
     }
 }
 public function testFromRow()
 {
     $row = array('timestamp' => $this->date->getTimestamp(), 'user' => 'test1', 'subject' => 'created_from');
     $activity = ActivityUsage::fromRow($row);
     $this->assertInstanceOf('OCA\\ocUsageCharts\\Entity\\Activity\\ActivityUsage', $activity);
     $this->assertEquals("created_from", $activity->getSubject());
     $this->assertEquals($this->date, $activity->getDate());
 }
 public function testValues()
 {
     $this->assertEquals('IAccountRecoveryService', $this->instance->getInterface());
     $this->assertEquals('ReportAccountRecoveryData', $this->instance->getMethod());
     $this->assertEquals('v1', $this->instance->getVersion());
     $this->assertEquals('POST', $this->instance->getRequestMethod());
     $this->assertEquals(['steamid' => 123456789, 'appid' => 321658, 'pathandfilename' => 'pathAndFileName', 'webcheaturl' => 'webCheatUrl', 'time_now' => $this->dateTime->getTimestamp(), 'time_started' => $this->dateTime->getTimestamp(), 'time_stopped' => $this->dateTime->getTimestamp(), 'cheatname' => 'cheatName', 'game_process_id' => 123435, 'cheat_process_id' => 456435], $this->instance->getParams());
 }
 /**
  * @param string $key
  * @param \DateTime $time
  *
  * @return bool
  */
 public function set($key, \DateTime $time)
 {
     $sh = new BlockShmop($this->getIdByKey($key), 10);
     if (!($old_time = $sh->read()) || $old_time < $time->getTimestamp()) {
         $sh->write($time->getTimestamp());
     }
     return true;
 }
Example #25
0
 /**
  * Get the html node for this element
  *
  * @param \DOMElement $node
  * @param \AppShed\Remote\XML\DOMDocument $xml
  * @param \AppShed\Remote\HTML\Settings $settings
  */
 protected function getHTMLNodeInner($node, $xml, $settings)
 {
     if (!empty($this->title)) {
         $node->appendChild($xml->createElement('div', ['class' => 'title', 'text' => $this->title]));
     }
     $node->appendChild($inner = $xml->createElement('div', 'textbox-container' . (empty($this->title) ? ' no-title' : '')));
     $inner->appendChild($xml->createElement('span', ['class' => 'picked', 'data-value' => $this->value ? $this->type == static::TYPE_DATE ? $this->value->getTimestamp() : $this->value->format('H:i') : null, 'data-placeholder' => $this->placeHolder, 'data-variable' => $this->variableName, 'data-picker-type' => $this->type, 'data-save-value' => $this->save]));
 }
 public static function getExpectedData()
 {
     $date = new \DateTime();
     $dateDue = new \DateTime();
     $dateDue->sub(new \DateInterval('P1D'));
     $dateNotDue = new \DateTime();
     $dateNotDue->add(new \DateInterval('P1D'));
     return array(array($dateDue->getTimestamp(), true), array($dateNotDue->getTimestamp(), false), array($dateDue->getTimestamp(), true, $date), array($dateNotDue->getTimestamp(), false, $date));
 }
Example #27
0
 /**
  * @return int
  */
 public function getSeconds()
 {
     $offset_time = clone $this->time;
     $offset_time->modify('+1 day 00:00:00');
     $offset = $offset_time->getTimestamp() - $this->time->getTimestamp();
     // offset to next day
     return $offset + rand(0, 86400);
     // 86400 is a 1 day
 }
 /**
  * {@inheritdoc}
  */
 public static function getTimeFrameBoundary($frequency, $timestamp)
 {
     // Create DateTime object to calculate the beginning of time period.
     $date_time = new \DateTime();
     $date_info = getdate($timestamp);
     switch ($frequency) {
         case \NegaWattNormalizerTimeManagerInterface::MINUTE:
             // Take the beginning of the previous minute.
             $date_time->setDate($date_info['year'], $date_info['mon'], $date_info['mday']);
             $hour = $date_info['hours'];
             // If timestampEnd was set to exact minute, go back one minute, otherwise go back to beginning of minute.
             $minute = 0 == $date_info['seconds'] ? $date_info['minutes'] - 1 : $date_info['minutes'];
             $date_time->setTime($hour, $minute, 0);
             break;
         case \NegaWattNormalizerTimeManagerInterface::HOUR:
             // Take the beginning of the previous hour.
             $date_time->setDate($date_info['year'], $date_info['mon'], $date_info['mday']);
             // If timestampEnd was set to exact hour, go back one hour, otherwise go back to beginning of hour.
             $hour = 0 == $date_info['minutes'] && 0 == $date_info['seconds'] ? $date_info['hours'] - 1 : $date_info['hours'];
             $date_time->setTime($hour, 0, 0);
             break;
         case \NegaWattNormalizerTimeManagerInterface::DAY:
             // Take the beginning of the previous day.
             // If timestampEnd was set to beginning of the day, go back one day, otherwise go back to beginning of the day.
             $day = 0 == $date_info['hours'] && 0 == $date_info['minutes'] && 0 == $date_info['seconds'] ? $date_info['mday'] - 1 : $date_info['mday'];
             $date_time->setDate($date_info['year'], $date_info['mon'], $day);
             $date_time->setTime(0, 0, 0);
             break;
         case \NegaWattNormalizerTimeManagerInterface::MONTH:
             // Take the beginning of the 1st day of the previous month.
             // If timestampEnd was set to beginning of the month, go back one month, otherwise go back to beginning of the month.
             $month = 0 == $date_info['hours'] && 0 == $date_info['minutes'] && 0 == $date_info['seconds'] && 1 == $date_info['mday'] ? $date_info['mon'] - 1 : $date_info['mon'];
             $date_time->setDate($date_info['year'], $month, 1);
             $date_time->setTime(0, 0, 0);
             if ($date_time->getTimestamp() == $timestamp) {
                 // If daylight saving time was changed at the 1st fo the month, getdate()
                 // will return hour 01:00 for hour 00:00, so setDate and setTime will
                 // return us to the same timestamp as we began. In order to overcome
                 // the problem, decrease the month and call setDate and setTime again.
                 $month--;
                 $date_time->setDate($date_info['year'], $month, 1);
                 $date_time->setTime(0, 0, 0);
             }
             break;
         case \NegaWattNormalizerTimeManagerInterface::YEAR:
             // Take the beginning of the 1st day of the previous year.
             // If timestampEnd was set to beginning of the month, go back one month, otherwise go back to beginning of the month.
             $year = 0 == $date_info['hours'] && 0 == $date_info['minutes'] && 0 == $date_info['seconds'] && 0 == $date_info['yday'] ? $date_info['year'] - 1 : $date_info['year'];
             $date_time->setDate($year, 1, 1);
             $date_time->setTime(0, 0, 0);
             break;
         default:
             // Not a known frequency.
             throw new \Exception(format_string('Cannot figure out frequency "@frequency".', array('@frequency' => \NegaWattNormalizerTimeManagerBase::frequencyToStr($frequency))));
     }
     return $date_time->getTimestamp();
 }
Example #29
0
 /**
  * @param string $dateFormat see syntax for php's strftime() function
  *
  * @return string
  */
 function getDaysText($dateFormat = "%B %d")
 {
     //strftime must be used for non-english support
     if ($this->startDate == $this->endDate) {
         return strftime($dateFormat, $this->startDate->getTimestamp());
     } else {
         return strftime($dateFormat, $this->startDate->getTimestamp()) . ' - ' . strftime($dateFormat, $this->endDate->getTimestamp());
     }
 }
Example #30
0
 /**
  * @return int
  */
 public function getSeconds()
 {
     $offset_time = clone $this->time;
     $offset_time->modify('+1 week 00:00:00');
     $offset = $offset_time->getTimestamp() - $this->time->getTimestamp();
     // offset to next week
     return $offset + rand(0, 604800);
     // 604800 is a 1 week
 }