Ejemplo n.º 1
0
 /**
  * Parse a sentence for time
  *
  * @param string $text
  * @param bool $replace_words
  *
  * @return string|array
  */
 function parse_time($text, $replace_words = false)
 {
     $matches = [];
     if ($replace_words) {
         $text = strtolower($text);
         $phrases = ['0:00' => 'midnight', '12:00' => 'noon', '12:00' => 'midday'];
         foreach ($phrases as $key => $phrase) {
             $text = str_replace($phrase, $key, $text);
         }
     }
     preg_match_all('/(\\d{1,2}[\\:]?(\\d{1,2})?\\s?(am|pm)?)/i', $text, $matches);
     $matches = array_slice($matches[0], 0, 2);
     if (empty($matches[0])) {
         return false;
     }
     $results = array_map(function ($match) {
         if (is_array($match)) {
             return [date_parse(trim($match[0])), date_parse(trim($match[1]))];
         }
         return date_parse(trim($match));
     }, $matches);
     $results = array_map(function ($result) {
         $is_nested = isset($result[1]);
         $items = $is_nested ? $result : [$result];
         for ($i = 0; $i < count($items); $i++) {
             $items[$i]['period'] = $items[$i]['hour'] > 12 ? 'PM' : 'AM';
         }
         return $is_nested ? $items : $items[0];
     }, $results);
     return isset($results[1]) ? $results : $results[0];
 }
Ejemplo n.º 2
0
 /**
  * @param $to
  * @param $data
  * @return bool
  */
 public function call_for_papers($to, $data)
 {
     $this->CI->load->library('parser');
     $view_data = array('journal_name' => $data['journal_name'], 'issue' => $data['issue'], 'volume' => $data['volume'], 'paper_open_date' => date_parse($data['open_date'])['day'], 'paper_open_month' => date_parse($data['open_date'])['month'], 'paper_open_year' => date_parse($data['open_date'])['year'], 'deadline_date' => date_parse($data['collection_date'])['day'], 'deadline_month' => date_parse($data['collection_date'])['month'], 'deadline_year' => date_parse($data['collection_date'])['year'], 'publication_date' => date_parse($data['publishing_date'])['day'], 'publication_month' => date_parse($data['publishing_date'])['month'], 'publication_year' => date_parse($data['publishing_date'])['year'], 'link' => $data['registration_link'], 'chief_editor_email' => $data['chief_editor_email']);
     $body_string = $this->CI->parser->parse('email/call_for_papers', $view_data, TRUE);
     return $this->send($to, "Call for Papers", $body_string);
 }
 public function collectData(array $param)
 {
     function fetchArticle($link)
     {
         $page = file_get_html($link);
         $contenu = $page->find(".article-text")[0];
         return strip_tags($contenu);
     }
     $html = '';
     $html = file_get_html('http://www.courrierinternational.com/article') or $this->returnError('Error.', 500);
     $element = $html->find(".type-normal");
     $article_count = 1;
     foreach ($element as $article) {
         $item = new \Item();
         $item->uri = "http://www.courrierinternational.com" . $article->find("a")[0]->getAttribute("href");
         $item->content = fetchArticle("http://www.courrierinternational.com" . $article->find("a")[0]->getAttribute("href"));
         $item->title = strip_tags($article->find("h2")[0]);
         $dateTime = date_parse($article->find("time")[0]);
         $item->timestamp = mktime($dateTime['hour'], $dateTime['minute'], $dateTime['second'], $dateTime['month'], $dateTime['day'], $dateTime['year']);
         $this->items[] = $item;
         $article_count++;
         if ($article_count > 5) {
             break;
         }
     }
 }
Ejemplo n.º 4
0
 /**
  * 
  */
 public function is_valid_datetime($date)
 {
     // is that a date
     $parsed_date = date_parse((string) $date);
     if (!$parsed_date) {
         return false;
     }
     // if this is a date in an expected format
     if (empty($parsed_date['errors'])) {
         $datetime = explode(' ', (string) $date);
         $no = count($datetime);
         if ($no === 1) {
             $format = 'Y-m-d';
         } elseif ($no === 2) {
             $not = count(explode(':', $datetime[1]));
             if ($not === 2) {
                 $format = 'Y-m-d H:i';
             } elseif ($not === 3) {
                 $format = 'Y-m-d H:i:s';
             } else {
                 return false;
             }
         } else {
             return false;
         }
     } else {
         // if this is a date but in a different format
         $format = 'Y-m-d H:i:s';
     }
     return $format;
 }
Ejemplo n.º 5
0
 private function parseDateOptions($withDates)
 {
     $this->fineDates = "";
     if (empty($_POST['doodle_dates'])) {
         app_controller::$err->add('post_empty_doodleDates');
         return;
     }
     $date_string = app_controller::$strcln->esc($_POST['doodle_dates']);
     //exit($date_string);
     $date_array = explode(",", $date_string);
     //exit(print_r($date_array));
     $this->fineDates = "";
     $date_array_count = count($date_array);
     $date_array_counter = 0;
     foreach ($date_array as $date) {
         $date_array_counter++;
         if (!($parsed_date = date_parse($date))) {
             app_controller::$err->add('date_parser_failed');
             return;
         }
         $this->fineDates .= $parsed_date['day'] . "." . $parsed_date['month'] . "." . $parsed_date['year'];
         if ($date_array_count === $date_array_counter) {
         } else {
             $this->fineDates .= ",";
         }
     }
     $this->makeQuery($withDates);
 }
Ejemplo n.º 6
0
 /**
  * http://yourproject/reportes/inscripciones
  */
 public function inscripciones()
 {
     //verificar sesion de usuario
     if (!$this->validUser()) {
         return false;
     }
     // verificar si hay datos POST
     if (isset($_POST["monthdate"]) && $_POST["monthdate"] != null) {
         $partes = explode("/", $_POST["monthdate"]);
         $mes = $partes[0];
         $anho = $partes[1];
     } else {
         //usar la fecha actual
         $today = date("Y-m-d");
         $dateAtributes = date_parse($today);
         $mes = $dateAtributes['month'];
         $anho = $dateAtributes['year'];
         //anteponer un cero a los meses con valor numerico menor que diez
         $mes = $mes < 10 ? "0" . $mes : $mes;
     }
     // cargar modelo, ejecutar la accion, pasar los datos a una variable
     $model = $this->loadModel('PersonasModel');
     try {
         $personaList = $model->listInscritosEnMes($mes, $anho);
     } catch (Exception $e) {
         $this->errorMessageView($e->getMessage());
         return;
     }
     // cargar modelo de pagos para averiguar el nombre del mes
     $pagos_model = $this->loadModel('PagosModel');
     $nombreMes = $pagos_model->nombreMes((int) $mes);
     // mostrar vista del reporte
     require 'application/reports/repinscripcionesdemes.php';
 }
Ejemplo n.º 7
0
 public static function generateUniqueName($title, $year)
 {
     $name_base = str_replace(array_keys(self::$TRANSLITERATABLE_CHARACTERS), array_values(self::$TRANSLITERATABLE_CHARACTERS), $title);
     $name_base = strtolower($name_base);
     $name_base = preg_replace("/[']/", '', $name_base);
     $name_base = preg_replace("/[^a-z0-9]/", '_', $name_base);
     $name_base = preg_replace('/_+/', '_', $name_base);
     if (strlen($year) > 4) {
         $year = date_parse($year);
         $year = $year["year"];
     }
     $approved = false;
     $try = 0;
     while (!$approved) {
         $number_length = 0;
         if ($try > 0) {
             $number_length = strlen($try) + 1;
         }
         $name = substr($name_base, 0, 254 - strlen($year) - $number_length);
         $name .= '_' . $year;
         if ($try > 0) {
             $name .= '_' . $try;
         }
         $result = null;
         $query = new GameQuery();
         $result = $query->findOneByName($name);
         if ($result != null) {
             $try++;
         } else {
             return $name;
         }
     }
 }
 /**
  * Parses given date/time of given timezone and converts to UTC.
  * If no timezone is given, a UTC date is expected.
  *
  * @param string $date_
  * @param \Components\Timezone $timezone_
  *
  * @return \Components\Date
  */
 public static function parse($date_, Timezone $timezone_ = null, $pattern_ = null)
 {
     $parsed = @date_parse($date_);
     if (null === $timezone_) {
         if (isset($parsed['zone'])) {
             $timezone_ = Timezone::forOffset($parsed['zone'] / 60);
         }
     }
     if (null === $timezone_) {
         $timezone_ = Timezone::utc();
     }
     if (null === $pattern_) {
         $pattern_ = I18n::translate('common/datetime/pattern/parse');
     }
     if (isset($parsed['errors_count']) && 0 < (int) $parsed['errors_count']) {
         $date = \DateTime::createFromFormat($pattern_, $date_, $timezone_->internal());
     } else {
         extract($parsed);
         $date = new \DateTime(sprintf('%1$d-%2$d-%3$d %4$d:%5$d:%6$d', $year, $month, $day, $hour, $minute, $second), $timezone_->internal());
     }
     if (!$date) {
         throw new Exception_IllegalArgument('type/date', 'Unable to parse given date. Try specifying a matching pattern.');
     }
     $date->setTimezone(Timezone::utc()->internal());
     return new static($date);
 }
Ejemplo n.º 9
0
 function local_time()
 {
     $traveller_info = $this->traveller_info();
     $city_info = $this->city_info($traveller_info->traveller->current_city->geoname_id);
     $date = date_parse($city_info->city->localtime);
     return date('g:i A', strtotime($date['hour'] . ":" . $date['minute']));
 }
Ejemplo n.º 10
0
 /**
  * @param string $filename
  * @return array
  */
 public static function document_pdf_metadata($filename)
 {
     $result = [];
     exec(PATH_PDFINFO . " '" . addslashes($filename) . "'", $result);
     $seiten = 0;
     $datum = "";
     if (preg_match("/Pages:\\s*([0-9]+)/siu", implode("\n", $result), $matches_page)) {
         $seiten = IntVal($matches_page[1]);
     }
     if (preg_match("/CreationDate:\\s*([a-z0-9 :]+)\n/siu", implode("\n", $result), $matches_date)) {
         $datum = date_parse($matches_date[1]);
         if ($datum && isset($datum["year"]) && $datum["year"] > 1990) {
             $datum = $datum["year"] . "-" . $datum["month"] . "-" . $datum["day"] . " " . $datum["hour"] . ":" . $datum["minute"] . ":" . $datum["second"];
         } else {
             $datum = "0000-00-00 00:00:00";
         }
     }
     if ($seiten > 0) {
         return ["seiten" => $seiten, "datum" => $datum];
     }
     $result = [];
     exec(PATH_IDENTIFY . " {$filename}", $result);
     $anzahl = 0;
     foreach ($result as $res) {
         if (strpos($res, "DirectClass")) {
             $anzahl++;
         }
     }
     return ["seiten" => $anzahl, "datum" => $datum];
 }
Ejemplo n.º 11
0
 function findWeekday($date)
 {
     date_default_timezone_set("UTC");
     $f_date = date_create($date);
     $base_date = date_create("2015-08-13");
     $output = "Thursday";
     $list_of_days = array("Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday");
     $p_date = date_parse($date);
     if ($p_date["error_count"] == 0 && checkdate($p_date["month"], $p_date["day"], $p_date["year"])) {
         $days = $base_date->diff($f_date);
         $pos_or_neg = $days->format('%R');
         $days = $days->format('%a');
         $days = $days % 7;
         if ($pos_or_neg == "-") {
             if ($days == 1) {
                 $days = 6;
             } elseif ($days == 2) {
                 $days = 5;
             } elseif ($days == 3) {
                 $days = 4;
             } elseif ($days == 4) {
                 $days = 3;
             } elseif ($days == 5) {
                 $days = 2;
             } elseif ($days == 6) {
                 $days = 1;
             }
         }
         $output = $list_of_days[$days];
     } else {
         $output = "ERROR";
     }
     $output = array($output, $date);
     return $output;
 }
Ejemplo n.º 12
0
function get_xsddatetime($date = '', $bkeep = false)
{
    if (empty($date)) {
        //$datetime_lastmodified = date_create();
        //$datetime_lastmodified = date_format($datetime_lastmodified, "Y-m-d\TH:i:s\Z");
        return false;
        //date("Y-m-d\TH:i:s\Z");
    } else {
        //		date_default_timezone_set("GMT");
        $temp = date_parse($date);
        if (!empty($temp) && $temp['year'] !== false && $temp['month'] !== false && $temp['day'] !== false) {
            $ret = sprintf("%04d-%02d-%02d", $temp['year'], $temp['month'], $temp['day']);
            if ($temp['hour'] !== false && $temp['minute'] !== false && $temp['second'] !== false) {
                return $ret . sprintf("T%02d:%02d:%02dZ", $temp['hour'], $temp['minute'], $temp['second']);
            } else {
                return $ret;
            }
        } else {
            if ($bkeep) {
                return $date;
            } else {
                return false;
            }
        }
    }
}
Ejemplo n.º 13
0
 function getStats()
 {
     $output = '';
     $q_status = $this->modx->newQuery('msOrderStatus', array('active' => 1));
     $q_status->select('id,name,color');
     if ($q_status->prepare() && $q_status->stmt->execute()) {
         while ($row = $q_status->stmt->fetch(PDO::FETCH_ASSOC)) {
             //$output[$row['id']] = $row;
             $output['total_counts'][$row['id']] = array('name' => $row['name'], 'color' => $row['color'], 'count_orders' => $this->modx->getCount('msOrder', array('status' => $row['id'])));
         }
     }
     $q_stats_month = $this->modx->newQuery('msOrder');
     $q_stats_month->select('status,`createdon`, month(`createdon`) AS `order_month`, count(*) AS `order_count`, SUM(cart_cost) AS order_cost');
     $q_stats_month->groupby('month(`createdon`), status');
     $q_stats_month->sortby('createdon', ASC);
     if ($q_stats_month->prepare() && $q_stats_month->stmt->execute()) {
         $output['cart_cost'] = 0;
         $output['cart_count'] = 0;
         while ($row = $q_stats_month->stmt->fetch(PDO::FETCH_ASSOC)) {
             $date = date_parse($row['createdon']);
             $output['stats_month'][$date['year'] . '-' . $date['month']][$row['status']] = array('total_cost' => $row['order_cost'], 'count_orders' => $row['order_count'], 'status' => $row['status']);
             $output['cart_cost'] += $row['order_cost'];
             $output['cart_count'] += $row['order_count'];
         }
         $output['cart_cost'] = number_format($output['cart_cost'], 2, ',', ' ');
         $output['users_count'] = $this->modx->getCount('modUser', array('active' => 1, 'primary_group' => 0));
     }
     return $output;
 }
Ejemplo n.º 14
0
 public function formatDateRange()
 {
     $startDateArray = date_parse($this->EventStartDate);
     $endDateArray = date_parse($this->EventEndDate);
     if ($startDateArray["year"] == $endDateArray["year"] && $startDateArray["month"] == $endDateArray["month"] && $startDateArray["day"] == $endDateArray["day"]) {
         // single day range
         return date('M d, Y', strtotime($this->EventStartDate));
     } else {
         if ($startDateArray["year"] == $endDateArray["year"] && $startDateArray["month"] == $endDateArray["month"]) {
             // multi-day, single month range
             $value = date('M d - ', strtotime($this->EventStartDate));
             $value .= date('d, Y', strtotime($this->EventEndDate));
             return $value;
         } else {
             if ($startDateArray["year"] == $endDateArray["year"]) {
                 // same year, spanning months (there days as well)
                 $value = date('M d - ', strtotime($this->EventStartDate));
                 $value .= date('M d, Y', strtotime($this->EventEndDate));
                 return $value;
             } else {
                 // must be different years (therefore months and days as well)
                 $value = date('M d, Y - ', strtotime($this->EventStartDate));
                 $value .= date('M d, Y', strtotime($this->EventEndDate));
                 return $value;
             }
         }
     }
 }
Ejemplo n.º 15
0
 public function reportsAction(Request $request)
 {
     $users = DB::select('select id, first_name, last_name, email from users');
     if ($request->isMethod('post')) {
         $id = substr($request->input('email'), strpos($request->input('email'), ":") + 2);
         $year = $request->input('year');
         $month = $request->input('month');
         $events = DB::select('select users.first_name, events.*, transport.name as t_name, transport.load_consumption,
               transport.moving_consumption, transport.stat_consumption
               from users inner join events on users.id = events.user_id
               left join transport on events.vehicle_id = transport.id
               where year(events.date) = ? and month(events.date) = ?
               AND users.id = ?', [$year, $month, $id]);
         $calc = [];
         foreach ($events as $event) {
             $parsed_arrive = date_parse($event->client_arrive);
             $parsed_leave = date_parse($event->client_leave);
             $hours['arrive'] = $parsed_arrive['hour'] + $parsed_arrive['minute'] / 60;
             $hours['leave'] = $parsed_leave['hour'] + $parsed_leave['minute'] / 60;
             $hours['actual'] = $hours['leave'] - $hours['arrive'] - $event->min_spent / 60;
             $calc[$event->id]['distance'] = (int) $event->spidometer_finish - (int) $event->spidometer_start;
             $calc[$event->id]['fuel'] = $calc[$event->id]['distance'] / 100 * $event->moving_consumption + $event->min_spent / 60 * $event->load_consumption + $hours['actual'] * $event->stat_consumption;
         }
         //        die(var_dump($calc));
         return view('admin/reports', ['events' => $events, 'calc' => $calc, 'users' => $users]);
     }
     return view('admin/reports', ['users' => $users]);
 }
Ejemplo n.º 16
0
/**
 * Retrieve a gig object with associated venue.
 *
 * If the $post parameter is omitted get_post() defaults to the current
 * post in the WordPress Loop.
 *
 * @since 1.0.0
 *
 * @param int|object $post Optional post ID or object. Default is global $post object.
 * @return object Post with additional gig info.
 */
function get_audiotheme_gig($post = null)
{
    $post = get_post($post);
    $gig_id = $post->ID;
    $post->gig_datetime = get_post_meta($gig_id, '_audiotheme_gig_datetime', true);
    $post->gig_time = '';
    $post->tickets_price = get_post_meta($gig_id, '_audiotheme_tickets_price', true);
    $post->tickets_url = get_post_meta($gig_id, '_audiotheme_tickets_url', true);
    // determine the gig time
    $gig_time = get_post_meta($post->ID, '_audiotheme_gig_time', true);
    $t = date_parse($gig_time);
    if (empty($t['errors'])) {
        $post->gig_time = mysql2date(get_option('time_format'), $post->gig_datetime);
    }
    $post->venue = null;
    if (isset($post->connected[0]) && isset($post->connected[0]->ID)) {
        $post->venue = get_audiotheme_venue($post->connected[0]->ID);
    } elseif (!isset($post->connected)) {
        $venues = get_posts(array('post_type' => 'audiotheme_venue', 'connected_type' => 'audiotheme_venue_to_gig', 'connected_items' => $post->ID, 'nopaging' => true, 'suppress_filters' => false));
        if (!empty($venues)) {
            $post->venue = get_audiotheme_venue($venues[0]->ID);
        }
    }
    return $post;
}
Ejemplo n.º 17
0
 public function ago($dt)
 {
     $dt = date_parse($dt);
     $now = date_parse(date("Y-m-d H:i:s"));
     $suffix = " left";
     $nowdate = strtotime($dt['year'] . '-' . $dt['month'] . '-' . $dt['day']);
     $enddate = strtotime($now['year'] . '-' . $now['month'] . '-' . $now['day']);
     $days = ($nowdate - $enddate) / (24 * 60 * 60);
     if ($now['year'] != $dt['year']) {
         return $this->pluralize($dt['year'] - $now['year'], "year") . $suffix;
     }
     if ($now['month'] != $dt['month'] && $days > 28) {
         return $this->pluralize($dt['month'] - $now['month'], "month") . $suffix;
     } elseif ($days > 0) {
         return $this->pluralize($days, "day") . $suffix;
     }
     if ($now['day'] != $dt['day']) {
         return $this->pluralize($dt['day'] - $now['day'], "day") . $suffix;
     }
     if ($now['hour'] != $dt['hour']) {
         return $this->pluralize($dt['hour'] - $now['hour'], "hour") . $suffix;
     }
     if ($now['minute'] != $dt['minute']) {
         return $this->pluralize($dt['minute'] - $now['minute'], "minute") . $suffix;
     }
     if ($now['second'] != $dt['second']) {
         return $this->pluralize($dt['second'] - $now['second'], "second") . $suffix;
     }
     return "just now";
 }
Ejemplo n.º 18
0
 public function testDateParse()
 {
     $arr = date_parse('01/01/2001');
     $this->assertEquals(1, $arr['day']);
     $this->assertEquals(1, $arr['month']);
     $this->assertEquals(2001, $arr['year']);
 }
 public static function subDays($date, $days)
 {
     $d = self::formatDate($date);
     $d = date_parse($d);
     $d = mktime($d['hour'], $d['minute'], $d['second'], $d['month'], $d['day'] - $days, $d['year']);
     return self::formatDate($d);
 }
Ejemplo n.º 20
0
 function readContent()
 {
     $data = read_xml_file($this->server, $this->port, $this->url);
     if (strlen($data) > 0) {
         $dom = new domDocument();
         $dom->loadXML(substr($data, 0, strrpos($data, '>') + 1));
         $arrFeeds = array();
         $count = 0;
         foreach ($dom->getElementsByTagName('item') as $node) {
             if (function_exists('date_parse')) {
                 $date_raw = date_parse($node->getElementsByTagName('pubDate')->item(0)->nodeValue);
                 //$date = date('H:i j.m.Y', mktime($date_raw['hour'], $date_raw['minute'], $date_raw['second'], $date_raw['month'], $date_raw['day'], $date_raw['year']));
                 $date = date('j.m', mktime($date_raw['hour'], $date_raw['minute'], $date_raw['second'], $date_raw['month'], $date_raw['day'], $date_raw['year']));
             } else {
                 $date1 = explode(' ', $node->getElementsByTagName('pubDate')->item(0)->nodeValue);
                 $months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
                 $months_n = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
                 $time = explode(':', $date1[4]);
                 //$date = $time[0] . ':' . $time[1] . ' ' . intval($date1[1]) . '.' . str_replace($months, $months_n, $date1[2]) . '.' . $date1[3];
                 $date = intval($date1[1]) . '.' . str_replace($months, $months_n, $date1[2]);
             }
             $itemRSS = array('title' => mb_convert_case(!$this->decodeUTF ? utf8_decode($node->getElementsByTagName('title')->item(0)->nodeValue) : $node->getElementsByTagName('title')->item(0)->nodeValue, MB_CASE_UPPER, "UTF-8"), 'description' => substr(!$this->decodeUTF ? utf8_decode($node->getElementsByTagName('description')->item(0)->nodeValue) : $node->getElementsByTagName('description')->item(0)->nodeValue, 0, 60), 'link' => $node->getElementsByTagName('link')->item(0)->nodeValue);
             $itemRSS['date'] = $date;
             array_push($arrFeeds, $itemRSS);
             $count++;
             if ($count == $this->nr_of_posts) {
                 break;
             }
         }
         return $arrFeeds;
     }
     return null;
 }
Ejemplo n.º 21
0
 public function getFields($userIdList)
 {
     $fields = array();
     $qs = array();
     $qBdate = BOL_QuestionService::getInstance()->findQuestionByName('birthdate');
     if ($qBdate->onView) {
         $qs[] = 'birthdate';
     }
     $qSex = BOL_QuestionService::getInstance()->findQuestionByName('sex');
     if ($qSex->onView) {
         $qs[] = 'sex';
     }
     $questionList = BOL_QuestionService::getInstance()->getQuestionData($userIdList, $qs);
     foreach ($questionList as $uid => $q) {
         $fields[$uid] = array();
         $age = '';
         if (!empty($q['birthdate'])) {
             $date = UTIL_DateTime::parseDate($q['birthdate'], UTIL_DateTime::MYSQL_DATETIME_DATE_FORMAT);
             $age = UTIL_DateTime::getAge($date['year'], $date['month'], $date['day']);
         }
         if (!empty($q['sex'])) {
             $fields[$uid][] = array('label' => '', 'value' => BOL_QuestionService::getInstance()->getQuestionValueLang('sex', $q['sex']) . ' ' . $age);
         }
         if (!empty($q['birthdate'])) {
             $dinfo = date_parse($q['birthdate']);
         }
     }
     return $fields;
 }
Ejemplo n.º 22
0
 /**
  * Tries to normalize date and converts it to an date array
  *
  * @param $str
  * @return string|bool
  */
 static function parseDate($str)
 {
     $str = self::prepareDateValues($str);
     $date = date_parse($str);
     $dateStr = date('d/m/Y', strtotime($date['year'] . '-' . $date['month'] . '-' . $date['day']));
     return self::validDate($date) ? $dateStr : false;
 }
Ejemplo n.º 23
0
 public function process(array $documents, &$context)
 {
     $doc = $documents[self::URL_HISTORY];
     $dom = self::getDOM($doc);
     $xpath = new DOMXPath($dom);
     Database::delete('userhistory', ['user_id' => $context->user->id]);
     $data = [];
     $nodes = $xpath->query('//table//td[@class = \'borderClass\']/..');
     foreach ($nodes as $node) {
         //basic info
         $link = $node->childNodes->item(0)->childNodes->item(0)->getAttribute('href');
         preg_match('/(\\d+)\\/?$/', $link, $matches);
         $media = strpos($link, 'manga') !== false ? Media::Manga : Media::Anime;
         $mediaMalId = intval($matches[0]);
         $progress = Strings::makeInteger($node->childNodes->item(0)->childNodes->item(2)->nodeValue);
         //parse time
         //That's what MAL servers output for MG client
         if (isset($doc->headers['Date'])) {
             date_default_timezone_set('UTC');
             $now = strtotime($doc->headers['Date']);
         } else {
             $now = time();
         }
         date_default_timezone_set('America/Los_Angeles');
         $hour = date('H', $now);
         $minute = date('i', $now);
         $second = date('s', $now);
         $day = date('d', $now);
         $month = date('m', $now);
         $year = date('Y', $now);
         $dateString = $node->childNodes->item(2)->nodeValue;
         if (preg_match('/(\\d*) seconds? ago/', $dateString, $matches)) {
             $second -= intval($matches[1]);
         } elseif (preg_match('/(\\d*) minutes? ago/i', $dateString, $matches)) {
             $second -= intval($matches[1]) * 60;
         } elseif (preg_match('/(\\d*) hours? ago/i', $dateString, $matches)) {
             $minute -= intval($matches[1]) * 60;
         } elseif (preg_match('/Today, (\\d*):(\\d\\d) (AM|PM)/i', $dateString, $matches)) {
             $hour = intval($matches[1]);
             $minute = intval($matches[2]);
             $hour += ($matches[3] == 'PM' and $hour != 12) ? 12 : 0;
         } elseif (preg_match('/Yesterday, (\\d*):(\\d\\d) (AM|PM)/i', $dateString, $matches)) {
             $hour = intval($matches[1]);
             $minute = intval($matches[2]);
             $hour += ($matches[3] == 'PM' and $hour != 12) ? 12 : 0;
             $hour -= 24;
         } elseif (preg_match('/([a-z]+) (\\d*), (\\d*):(\\d\\d) (AM|PM)/i', $dateString, $matches)) {
             $month = date_parse($matches[1]);
             $month = intval($month['month']);
             $day = intval($matches[2]);
             $hour = intval($matches[3]);
             $minute = intval($matches[4]);
             $hour += ($matches[5] == 'PM' and $hour != 12) ? 12 : 0;
         }
         $timestamp = mktime($hour, $minute, $second, $month, $day, $year);
         date_default_timezone_set('UTC');
         $data[] = ['user_id' => $context->user->id, 'mal_id' => $mediaMalId, 'media' => $media, 'progress' => $progress, 'timestamp' => date('Y-m-d H:i:s', $timestamp)];
     }
     Database::insert('userhistory', $data);
 }
Ejemplo n.º 24
0
function getMySQLFormat($dateTime, $round = 0)
{
    // format as YYYY-MM-DD HH:MM:SS
    $formatstr = $dateTime->format('Y-m-d H:i:s');
    // check if round is -1 to round down
    if ($round == -1) {
        // get the minutes
        $minutes = date_parse($formatstr)['minute'];
        // check if it already is at the nearest hour (if minutes = 0)
        if ($minutes != 0) {
            // subtract the minutes
            $dateTime->sub(date_interval_create_from_date_string("{$minutes} minutes"));
            // reset the string
            $formatstr = $dateTime->format('Y-m-d H:i:s');
        }
        // check if round is 1 to round up
    } else {
        if ($round == 1) {
            // get the minutes
            $minutes = date_parse($formatstr)['minute'];
            // check if it already is at the nearest hour (if minutes = 0)
            if ($minutes != 0) {
                // determine the minutes to be added
                $minutes = 60 - $minutes;
                // add the minutes
                $dateTime->add(date_interval_create_from_date_string("{$minutes} minutes"));
                // reset the string
                $formatstr = $dateTime->format('Y-m-d H:i:s');
            }
        }
    }
    // return the formatted string
    return $formatstr;
}
 public function collectData(array $param)
 {
     $html = '';
     $html = $this->file_get_html('http://www.courrierinternational.com/') or $this->returnError('Error.', 500);
     $element = $html->find("article");
     $article_count = 1;
     foreach ($element as $article) {
         $item = new \Item();
         $item->uri = $article->parent->getAttribute("href");
         if (strpos($item->uri, "http") === FALSE) {
             $item->uri = "http://courrierinternational.fr/" . $item->uri;
         }
         $page = $this->file_get_html($item->uri);
         $cleaner = new HTMLSanitizer();
         $item->content = $cleaner->sanitize($page->find("div.article-text")[0]);
         $item->title = strip_tags($article->find(".title")[0]);
         $dateTime = date_parse($page->find("time")[0]);
         $item->timestamp = mktime($dateTime['hour'], $dateTime['minute'], $dateTime['second'], $dateTime['month'], $dateTime['day'], $dateTime['year']);
         $this->items[] = $item;
         $article_count++;
         if ($article_count > 5) {
             break;
         }
     }
 }
Ejemplo n.º 26
0
 /**
  * Converts the given date to MonthName Day, Year at Hour:Minutes AM/PM
  * @param $date - the date information from SVN
  */
 public function setDate($date)
 {
     // replacing the T with a space so it can be parsed
     $date[strpos($date, "T")] = " ";
     $dateInfo = date_parse($date);
     $resultDate = $this->determineMonth($dateInfo['month']) . " " . $dateInfo['day'] . ", " . $dateInfo['year'] . " at " . $this->formatTime($dateInfo["hour"], $dateInfo["minute"]);
     $this->date = $resultDate;
 }
Ejemplo n.º 27
0
 public function testCanGetAsDateTime()
 {
     $now = new Date($this->datestring);
     $datenow = new DateTime($this->datestring);
     $parts = date_parse($datenow->format(DATE_W3C));
     $exptected = mktime($parts['hour'], $parts['minute'], $parts['second'], $parts['month'], $parts['day'], $parts['year']);
     $this->assertEquals($exptected, $now->Timestamp());
 }
Ejemplo n.º 28
0
function isLegalDate($date)
{
    $parseArr = date_parse($date);
    if (checkdate($parseArr["month"], $parseArr["day"], $parseArr["year"])) {
        return true;
    }
    return false;
}
Ejemplo n.º 29
0
function fecha_legible($input)
{
    $meses = array("zero", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
    $f = date_parse($input);
    //genera un array asociativo con información detallada de la fecha de input
    $fechaFormateada = $f['day'] . " de " . $meses[$f['month'] - 1] . " de " . $f['year'] . " " . $f['hour'] . ":" . $f['minute'];
    return $fechaFormateada;
}
Ejemplo n.º 30
0
 function format_date_for_sql($date)
 {
     if ($date == "") {
         return null;
     } else {
         $dateParts = date_parse($date);
         return $dateParts['year'] * 10000 + $dateParts['month'] * 100 + $dateParts['day'];
     }
 }